[英]How to sort an array of objects using another array for reference?
我想使用另一个只有 id 的数组对每个 id 为 object 的对象数组进行排序,例如:
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}
}
}
}
我正在使用 map 因为我认为这是大阵列的最佳方式,因为我正在构建一个音乐播放器,所以不知道用户有多少曲目
您可以使用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);
为什么不直接使用Array.prototpye.sort()
? 它既简单又快速。
const pre = document.querySelector('pre'); let object = [ {id: 2, name: 'carlos'}, {id: 1, name: 'maria'}, {id: 4, name: 'juan'}, {id: 3, name: 'pepe'} ]; const criteria = [1,2,3,4,5]; pre.innerText = 'object:' + JSON.stringify(object, null, 2) + '\n\n'; object.sort((a, b) => { return criteria[a.id] - criteria[b.id]; }); pre.innerText += 'sorted object:' + JSON.stringify(object, null, 2);
Sort an array using criteria from a second array: <pre></pre>
您可以利用Schwartzian transform
并根据另一个数组对数据进行排序。
const data = [ { id: 2, name: 'carlos' }, { id: 1, name: 'maria' }, { id: 4, name: 'juan' }, { id: 3, name: 'pepe' }, ], order = [4, 2, 3, 1, 5], result = data.map(o => { const index = order.indexOf(o.id); return [index, o]; }).sort((a, b) => a[0] - b[0]).map(([, o]) => o); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.