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.

3
  • data.items.sort( (a,b) => a.id - b.id ); Commented Feb 9, 2018 at 8:25
  • Is the second array already sorted by id? Commented Feb 9, 2018 at 8:32
  • Yes it is, but i want it to be ordered like it is in first array Commented Feb 9, 2018 at 8:35

2 Answers 2

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])
Sign up to request clarification or add additional context in comments.

1 Comment

I was thinking of something like this, but couldn't figure it out. They might be, thanks for showing me also the efficient way
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; }

1 Comment

Since i was already using lodash, i accepted answer of georg. But thank you for this answer really helpful to see it without lodash

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.