3

I want to my second array to be ordered by the attribute id as in the first array.

Here are my arrays

First array

data : 
  items:
    0: {id: 14, attributes: Array(1)}
    1: {id: 8, attributes: Array(1)}
    2: {id: 4, attributes: Array(1)}
    3: {id: 1, attributes: Array(2)}
    4: {id: 2045, attributes: Array(2)}

Second array

data : 
  items:
    0: {id: 1, name: "test Product 1"}
    1: {id: 4, name: "test Product 1"}
    2: {id: 8, name: "test Product 1"}
    3: {id: 14, name: "test Product 1"}
    4: {id: 2045, name: "test Product 1"}

I tried it like this:

Javascript - sort array based on another array

But I can't seem to get it working. I know this was asked a lot but I just can't figure it out.

Zenoo
  • 12,670
  • 4
  • 45
  • 69
MePo
  • 1,044
  • 2
  • 23
  • 48

2 Answers2

8

lodash

sorted = _.sortBy(items1, x => _.findIndex(items2, y => x.id === y.id))

If your arrays are fairly long, it might be more efficient to build an index first, and then sort by that:

index = _.fromPairs(_.map(items2, (x, i) => [x.id, i]));
sorted = _.sortBy(items1, x => index[x.id])
georg
  • 211,518
  • 52
  • 313
  • 390
  • I was thinking of something like this, but couldn't figure it out. They might be, thanks for showing me also the efficient way – MePo Feb 09 '18 at 08:40
3

You could sort by the indices of the first array.

items2.sort((a, b) =>
    items1.findIndex(({ id }) => a.id === id) -
    items1.findIndex(({ id }) => b.id === id));

var items1 = [{ id: 14, attributes: [1] }, { id: 8, attributes: [1] }, { id: 4, attributes: [1] }, { id: 1, attributes: [1] }, { id: 2045, attributes: [1, 2] }],
    items2 = [{ id: 1, name: "test Product 1" }, { id: 4, name: "test Product 1" }, { id: 8, name: "test Product 1" }, { id: 14, name: "test Product 1" }, { id: 2045, name: "test Product 1" }];

items2.sort((a, b) => items1.findIndex(({ id }) => a.id === id) - items1.findIndex(({ id }) => b.id === id));

console.log(items2);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Since i was already using lodash, i accepted answer of georg. But thank you for this answer really helpful to see it without lodash – MePo Feb 09 '18 at 08:41