[英]sort an object array based on property of another object array
i have two object arrays in js.dummy arrays are shown below. 我在js.dummy数组中有两个对象数组如下所示。
arr1=[{'id':1,'name':'David'},
{'id':2,'name':'Miles'},
{'id':3,'name':'John'},];
arr2=[{'id':2,'age':22},
{'id':3,'age':18},
{'id':1,'age':12},];
Can i sort arr1 in same order of ids as arr2. 我可以按照与arr2相同的ID顺序对arr1进行排序。 so arr1 becomes
所以arr1变成了
[{'id':2,'name':'Miles'},
{'id':3,'name':'John'},
{'id':1,'name':'David'},];
actual arrays have some 900 objects each.so is there any efficient method of achieving this? 实际的数组每个都有900个对象。那么有没有有效的方法来实现这一点?
reduce
the second array to a Map
indexed by id
s, then use Map.get
to identify the location of the id while sorting. 将第二个数组
reduce
为由id
s索引的Map
,然后使用Map.get
在排序时标识id的位置。 Map
s have guaranteed O(1) lookup time: Map
s保证了O(1)查找时间:
const arr1 = [{'id':1,'name':'David'},{'id':2,'name':'Miles'},{'id':3,'name':'John'},]; const arr2 = [{'id':2,'age':22},{'id':3,'age':18},{'id':1,'age':12},]; const ids = arr2.reduce((map, { id }, i) => map.set(id, i), new Map()); arr1.sort((a, b) => ids.get(a.id) - ids.get(b.id)); console.log(arr1);
Still, 900 objects is not much at all in the modern day. 尽管如此,在现代,900件物品并不多。
// cache arr1 id to index, id is key, index is value
let arr1IdToIndex = arr1.reduce((sum, cur, index) => (sum[cur.id] = index, sum), {})
let result = arr2.map(cur => arr1[arr1IdToIndex[cur.id]])
arr1 = result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.