0

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?

Andrew Halil
  • 1,195
  • 15
  • 15
  • 21
Bary
  • 53
  • 1
  • 2
  • 11
  • Does this answer your question? [How do I sort an array of objects based on the ordering of another array?](https://stackoverflow.com/questions/9755889/how-do-i-sort-an-array-of-objects-based-on-the-ordering-of-another-array) Get the array of `name`s via https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array – Heretic Monkey Nov 09 '21 at 12:29

1 Answers1

2

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.

Lesiak
  • 22,088
  • 2
  • 41
  • 65