我有一个库存,如下所示。
var arr1 = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[1, "Hair Pin"],
[5, "Microphone"]
];
我想按字母顺序对库存进行排序。我尝试使用简单的冒泡排序技术来做到这一点。但它显示错误 -“wrappedCompareFn 不是函数”。
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;
}
我的代码有问题吗?还有更好的方法对具有不同类型对象的多维数组进行排序吗?
最佳答案
您可以使用内置方法 Array#sort
使用自定义回调。
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>');
关于javascript - 对包含数字和字符串的二维数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37132853/