本文介绍了排序包含数字和字符串的二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个如下所示的清单。I have an Inventory as shown below.var arr1 = [ [21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]];我想按字母顺序对广告资源进行排序。我尝试使用一种简单的气泡排序技术来做到这一点。但是它显示了一个错误- wrappedCompareFn不是函数。I want to sort the inventory alphabetically. I tried using a simple bubble sort technique to do it. But it shows an error-"wrappedCompareFn is not a function".function sort(arr1){ //console.log("works");for(var i=0;i<arr1.length;i++){ for(var j=0;j<arr1.length;j++){ // console.log(arr1[j][1].localeCompare(arr1[i][1])); if(arr1[j][1].localeCompare(arr1[i][1])<0){ var tmp=arr1[i][1]; arr1[i][1]=arr1[j][1]; arr1[j][1]=tmp; } } } return arr1;}我的代码有问题吗??还有一种更好的方法可以对具有不同类型的对象的多维数组进行排序?Is there a problem with my code?? Also is there a better way to sort multidimensional arrays with different types of objects??推荐答案您可以使用内置方法 Array#sort 和自定义回调。You may use the build in method Array#sort with a custom callback. sort()方法对数组中的元素进行适当排序,然后返回数组。排序不一定稳定。默认的排序顺序是根据字符串Unicode代码点确定的。 The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points. var arr1 = [[1, "Hair Pin"], [21, "Bowling Ball"], [2, "Dirty Sock"], [5, "Microphone"]];arr1.sort(function (a, b) { return a[1].localeCompare(b[1]);});document.write('<pre>' + JSON.stringify(arr1, 0, 4) + '</pre>'); 这篇关于排序包含数字和字符串的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-12 22:55