根据规格对 JSON 个条目进行排序

Sort JSON entries in a numerical order with specification

我有一个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"}

我敢肯定,有一个简单的解决方案,但我找不到任何关于特定数字排序的信息。

在为

获得输出 运行 之后
 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});

你可以检查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"}];