Search code examples
javascriptlodash

How to order array by another array IDs (lodash / javascript)


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.


Solution

  • 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])