2

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?

2 Answers 2

6

reduce the second array to a Map indexed by ids, then use Map.get to identify the location of the id while sorting. Maps 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.

Sign up to request clarification or add additional context in comments.

Comments

1
// 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.