给定两个相同长度和相同内容的数组,如何根据共享属性将一个数组排序为与第二个数组相同的顺序?
的例子:
let array1 = [{id: 123, ...}, {id: 456, ...}, {id: 789, ...}] // order always stays the same
let array2 = [{id: 456, ...}, {id: 789, ...}, {id: 123, ...}] // order is always different
我如何排序array1这样:
array1[0].id
= 456array2[0].id
为456
循环第一个,并通过index:
let arr1 = [{id: 123}, {id: 456}, {id: 789}] // order always stays the same
let arr2 = [{id: 456}, {id: 789}, {id: 123}]
arr1.forEach((obj1, idx) => {
arr2[idx] = obj1
})
console.log(arr1, arr2)
假设array2有我们所关心的对象,而array1指定了排序顺序,使用它映射到排序数组来选择要排序的对象…
let array1 = [{id: 123 }, {id: 456 }, {id: 789, }]
let array2 = [{id: 456, name: '456' }, {id: 789, name: '789' }, {id: 123, name: '123' }]
let array2ElementsSortedByArray1 = array1.map(e => {
return array2.find(e2 => e2.id === e.id)
})
console.log(array2ElementsSortedByArray1)
您可以从array2
创建形状{id: index, ...}
的散列,然后使用它来对array1
的元素进行排序。这节省了每次迭代时find()
的成本。
let array1 = [{ id: 123, }, { id: 456, }, { id: 789, }] // order always stays the same
let array2 = [{ id: 456, }, { id: 789, }, { id: 123, }]
const
indeces = Object.fromEntries(array2.map(({ id }, i) => [id, i])), // { 456: 0, 789: 1, 123: 2 }
ordered = [];
array1.forEach(o => ordered[indeces[o.id]] = { ...o });
console.log(ordered)