首页 > 解决方案 > 如何使用另一个数组对对象数组进行排序以供参考?

问题描述

我想使用另一个只有 id 的数组对具有 id 每个对象的对象数组进行排序,例如:

object = [
 {id: 2, name: carlos},
 {id: 1, name: maria},
 {id: 4, name: juan},
 {id: 3, name: pepe},    //this is the array that i want to be sorted or create a copy to return it
]

    [1,2,3,4,5] //this is the array that i will use as reference to sort the first one

最终结果应该是:

object = [
 {id: 1, name: maria},
 {id: 2, name: carlos},
 {id: 3, name: pepe},
 {id: 4, name: juam},    //this is the array that i want to be sorted or create a copy to return it
]

我使用两个地图,但我总是得到未定义的数组:

array_to_be_sorted.map((objects) => {
  array_reference.map((id) => {
     if (objects.id === id) {
        return {...objects}
     }
  }    
}

我使用地图原因认为是大数组的最佳方式,因为我正在构建一个音乐播放器,所以不知道用户有多少曲目

标签: javascript

解决方案


您可以使用Array.prototype.sort()方法来获得结果。

const data = [
  { id: 2, name: 'carlos' },
  { id: 1, name: 'maria' },
  { id: 4, name: 'juan' },
  { id: 3, name: 'pepe' },
];

const order = [1, 2, 3, 4, 5];
data.sort((x, y) => order.indexOf(x.id) - order.indexOf(y.id));
console.log(data);

另一种使用Map Object它的解决方案比第一个更快。

const data = [
  { id: 2, name: 'carlos' },
  { id: 1, name: 'maria' },
  { id: 4, name: 'juan' },
  { id: 3, name: 'pepe' },
];

const order = [1, 2, 3, 4, 5];
const map = new Map();
order.forEach((x, i) => map.set(x, i));
data.sort((x, y) => map.get(x.id) - map.get(y.id));
console.log(data);


推荐阅读