I need to sort array based on another.
Arr1
const arr1 =[
{id: 74, name: 'Mat', type: 'bus'},
{id: 2, name: 'Johan', type: 'plane'}
{id: 25, name: 'Kevin', type: 'car'},
{id: 10, name: 'Mary', type: 'plane'},
{id: 34, name: 'Katrin', type: 'car'}
]
Arr2
const arr2 =[
{id: 25},
{id: 34},
{id: 10},
]
or without id ... it does not matter
const arr2 =["25","34", "10"]
What I want to get back is sorted array with the rest ids that is not in the second array
const arr1 =[
{id: 25, name: 'Kevin', type: 'car'},
{id: 34, name: 'Katrin', type: 'car'}
{id: 10, name: 'Mary', type: 'plane'},
{id: 74, name: 'Mat', type: 'bus'},
{id: 2, name: 'Johan', type: 'plane'}
]
I found several solutions, but no one of them deal with the rest of objects that are not in array2 (id:74 and id:2). Any suggestions?
2
Answers
Find indices of IDs and sort accordingly. You could also cache the indices in a Map, works a bit faster:
This should do it.