按编号顺序对JSON条目进行排序

时间:2018-10-23 14:03:49

标签: javascript arrays json sorting numeric

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

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

2 个答案:

答案 0 :(得分:2)

您可以检查[latest_record_date]是否为0,如果为0,请使用Infinity进行排序以确保所有位置都将放置在数组的末尾。

datasource_id   datasource_filter_column    first_calculation_formula   first_record_date   previous_calculation_formula    previous_record_date    latest_calculation_formula  latest_record_date
   1234abc           column1                 CONCAT('first ','entry')       18-Oct-18         CONCAT('second ','entry')         20-Oct-18             CONCAT('third ','entry')      23-Oct-18

答案 1 :(得分: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});