简体   繁体   English

javascript根据值重新排列数组索引

[英]javascript rearrange array index based on value

I have an array that look like this 我有一个看起来像这样的数组

var array = [{id:5},{id:1},{id:2}]

I want to rearrange the array index based on the id value from lowest to highest so it becomes 我想根据ID值从最低到最高重新排列数组索引,因此它变成

var newarray = [{id:1},{id:2},{id:5}]

I have been looking at sort() but I dont quite understand the logic behind it. 我一直在看sort(),但我不太了解其背后的逻辑。

To achieve this, you can use native array sort function which you can pass a callback as a compare function. 为此,可以使用本机数组排序函数,您可以将回调作为比较函数传递。

 var array = [{id:5},{id:1},{id:2}]; array.sort(function(a, b) { return a.id - b.id; }); console.log(array); //[{"id": 1 }, {"id": 2 }, {"id": 5 } ] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM