I have 2 arrays of objects
array1 = [
{
"name": "B",
"order": 1
},
{
"name": "C",
"order": 2
},
{
"name": "D",
"order": 3
},
{
"name": "B",
"order": 4
},
{
"name": "A",
"order": 5
}
]
array2 = [
{
"name": "B",
"order": 1,
"id": 3638
},
{
"name": "B",
"order": 1,
"id": 3661
},
{
"name": "C",
"order": 2,
"id": 3658
},
{
"name": "D",
"order": 3,
"id": 3659
},
{
"name": "A",
"order": 5,
"id": 3636
}
]
I need to sort array2 to match the same order of array1 based on the property name. In array2 there are 2 names properties equal with value B. These name B are together but i need the array to be in the exact order of array1. In array1 the first B is at index 0 and the second B is at index 3.
I made this attempts without luck.
array2.sort((a, b) => array1.indexOf(a.name) - array1.indexOf(b.name));
let sorted = array2.sort((a, b) => {
return array1.findIndex(p => p.name=== a.name) - array1.findIndex(p => p.name=== b.name);
});