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.
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.
Share Improve this question edited Feb 9, 2018 at 8:28 Zenoo 12.9k4 gold badges46 silver badges70 bronze badges asked Feb 9, 2018 at 8:21 MePoMePo 1,0742 gold badges23 silver badges51 bronze badges 3-
data.items.sort( (a,b) => a.id - b.id );
– gurvinder372 Commented Feb 9, 2018 at 8:25 - Is the second array already sorted by id? – gurvinder372 Commented Feb 9, 2018 at 8:32
- Yes it is, but i want it to be ordered like it is in first array – MePo Commented Feb 9, 2018 at 8:35
2 Answers
Reset to default 8lodash
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])
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; }