javascript - 如何使用另一个数组对对象数组进行排序以供参考?
问题描述
我想使用另一个只有 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}
}
}
}
我使用地图原因认为是大数组的最佳方式,因为我正在构建一个音乐播放器,所以不知道用户有多少曲目
解决方案
您可以使用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);
推荐阅读
- sql - 用纯 html 内容索引 PostgreSQL 数据库的最佳方法?
- vb.net - 无法附加调试 Visual Studio 2017
- reactjs - React Link无法打开heroku url
- javascript - 如何使用 REACT 访问被点击元素的子元素?
- javascript - 如何重写函数以便它可以在子类中使用
- pandas - 熊猫基于另一列赋值
- java - int x int y 和 int x,y 有什么区别
- video - ts视频怎么加水印?
- web-scraping - 有什么方法可以在不被验证码阻止的情况下抓取 Google 搜索结果?
- tableau-api - Tableau:字符串的 Previous_Value