Home > Software design >  Sort array of object by another array of object
Sort array of object by another array of object

Time:11-10

I have two arrays of objects with the same length.

one= 
[
    { id: 3, name: 'a'}, 
    { id: 5, name: 'b'},
    { id: 4, name: 'c'}
];

two= 
[
    { id: 7, name: 'b'}, 
    { id: 6, name: 'c'},
    { id: 2, name: 'a'}
];

I want to sort array 'two' by name property that depends on array 'one'.

My solution is

const tempArray = [];
one.forEach((x) => {
   tempArray.push(two.find(item => item.name === x.name));

But is there a way to do this without creating tempArray?

I mean a one line solution?

CodePudding user response:

You could use map function:

const tempArray = one.map(x => two.find(item => item.name === x.name));

Alternatively, if you are not striving for brevity:

const nameToPosMap = Object.fromEntries(one.map((x, idx) => [x.name, idx]));
two.sort((i1, i2) => nameToPosMap[i1.name] - nameToPosMap[i2.name])

This may be faster as it avoids repeated find calls.

  • Related