i have two object arrays in js.dummy arrays are shown below.
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. so arr1 becomes
[{'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?
reduce
the second array to a Map
indexed by id
s, then use Map.get
to identify the location of the id while sorting. Map
s have guaranteed O(1) lookup time:
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.
// 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.