Mad*_*dan 4 javascript arrays sorting
我正在编写一个脚本,其中我必须根据内部数组的第二个元素对数组的 arr 进行排序。例如,下面我提到了数组:
var newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
Run Code Online (Sandbox Code Playgroud)
我想根据内部数组中的所有字符串值对该数组进行排序。所以结果应该是:
var result = [
[67, "Bowling Ball"],
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[7, "Toothpaste"]
];
Run Code Online (Sandbox Code Playgroud)
为此,我编写了以下脚本:还有其他方法可以做同样的事情吗?可能没有创建对象?
var newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
Run Code Online (Sandbox Code Playgroud)
你可以使用Array#sort
该
sort()
方法对数组的元素进行就地排序并返回该数组。该排序不一定是稳定的。默认排序顺序是根据字符串 Unicode 代码点。
该
localeCompare()
方法返回一个数字,指示引用字符串在排序顺序中是位于给定字符串之前还是之后,或者是否与给定字符串相同。
var newInv = [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]];
newInv.sort(function (a, b) {
return a[1].localeCompare(b[1]);
});
console.log(newInv);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3172 次 |
最近记录: |