在我的 index.html 中,我从服务器接收的数据按以下顺序排列:
[{ id: 1, keyOne: valueOne, keyTwo: valueTwo},
{ id: 2, keyOne: valueOne, keyTwo: valueTwo},
{ id: 3, keyOne: valueOne, keyTwo: valueTwo},
{ id: 4, keyOne: valueOne, keyTwo: valueTwo}]
我想按降序排序:
[{ id: 4, keyOne: valueOne, keyTwo: valueTwo},
{ id: 3, keyOne: valueOne, keyTwo: valueTwo},
{ id: 2, keyOne: valueOne, keyTwo: valueTwo},
{ id: 1, keyOne: valueOne, keyTwo: valueTwo}]
我已经尝试了Stackoverflow的多种方法,但是找不到完美的匹配。
我该怎么做?
答案 0 :(得分:1)
使用数组的sort()方法很容易做到:
const input = [
{id: 1, keyOne: "valueOne", keyTwo: "valueTwo"},
{id: 2, keyOne: "valueOne", keyTwo: "valueTwo"},
{id: 3, keyOne: "valueOne", keyTwo: "valueTwo"},
{id: 4, keyOne: "valueOne", keyTwo: "valueTwo"}
];
let sortedInput = input.slice(0).sort((a,b) => b.id - a.id);
console.log(sortedInput);
答案 1 :(得分:0)
请参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
my_array.sort(function(a, b) {
if (a.id > b.id) return -1;
else if (a.id < b.id) return 1;
else return 0;
});
答案 2 :(得分:0)
const JsonArray= [
{ id: 1, keyOne: "valueOne", keyTwo: "valueTwo"},
{ id: 2, keyOne: "valueOne", keyTwo: "valueTwo"},
{ id: 3, keyOne: "valueOne", keyTwo: "valueTwo"},
{ id: 4, keyOne: "valueOne", keyTwo: "valueTwo"}
];
let JsonReversedArray= JsonArray.reverse();
console.log(JsonReversedArray);
颠倒对象数组中元素的顺序
但这在这种情况下不起作用
const JsonArray= [
{ id: 1, keyOne: "valueOne", keyTwo: "valueTwo"},
{ id: 5, keyOne: "valueOne", keyTwo: "valueTwo"},
{ id: 3, keyOne: "valueOne", keyTwo: "valueTwo"},
{ id: 4, keyOne: "valueOne", keyTwo: "valueTwo"}
];
如您在此处看到的,如果您的ID已经正确排列,则reverse方法将对您的数组进行反转:
let JsonReversedArray= JsonArray.sort((a,b) => b.id - a.id);
这种情况对这种情况是正确的