我有一个JSON,我可以成功地对数字进行排序。
data["example"].sort(function (a, b) {
return a["one"] - b["two"];
});
// Output:
0: {location: "0"}
1: {location: "0"}
2: {location: "0"}
3: {location: "0"}
4: {location: "0"}
5: {location: "0"}
6: {location: "0"}
7: {location: "0"}
8: {location: "1"}
9: {location: "2"}
10: {location: "3"}
11: {location: "4"}
12: {location: "5"}
13: {location: "6"}
14: {location: "7"}
但是,我希望它从1
到∞
开始排序,然后附加所有0
。
喜欢这个:
0: {location: "1"}
1: {location: "2"}
2: {location: "3"}
3: {location: "4"}
4: {location: "5"}
5: {location: "6"}
6: {location: "7"}
7: {location: "0"}
8: {location: "0"}
9: {location: "0"}
10: {location: "0"}
11: {location: "0"}
12: {location: "0"}
13: {location: "0"}
14: {location: "0"}
我敢肯定,有一个简单的解决方案,但我找不到关于这种特定数字排序的任何信息。
您可以检查location
是否为 0,如果是,请使用Infinity
进行排序以确保所有位置都将放置在数组的末尾。
let arr = [{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"1"},{"location":"2"},{"location":"3"},{"location":"4"},{"location":"5"},{"location":"6"},{"location":"7"}];
arr.sort(function(a, b) {
return (a.location === "0" ? Infinity : a.location) - (b.location === "0" ? Infinity : b.location);
});
console.log(arr);
// Output:
// [{"location":"1"},{"location":"2"},{"location":"3"},{"location":"4"},{"location":"5"},{"location":"6"},{"location":"7"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"},{"location":"0"}];
在获取输出运行后
for (let i = 0; i < array.length; i++) {
array[i].location = i+1;
}
或使用类似地图
let counter = 1;
data["example"].sort(function (a, b) {
return a["one"] - b["two"];
}).map(c=> {c.location = counter++;return c});