Reputation: 53
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?
Upvotes: 0
Views: 618
Reputation: 25966
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.
Upvotes: 2