0

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?

Vova
  • 750
  • 11
  • 26
  • 1
    Did you find [Javascript - sort array based on another array](/q/13304543/4642212)? Have you read the [documentation](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)? Start with `const arr2 = [ 25, 34, 10 ];` (numbers, not strings), and `arr1.sort((a, b) => arr2.indexOf(a.id) - arr2.indexOf(b.id))`, then try to think about what happens when `indexOf` returns `-1`, and what happens when `arr2.indexOf(a.id) - arr2.indexOf(b.id)` is `0`. – Sebastian Simon Jun 13 '23 at 14:26

1 Answers1

1

This should do it.

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 = [25, 34, 10],
     
     getIndex = (n, a) => a.includes(n) ? a.indexOf(n) : a.length;

     sorted = arr1.sort(
        (a,b) => 
        getIndex(a.id, arr2) - getIndex(b.id, arr2)
     );

console.log( sorted );
PeterKA
  • 24,158
  • 5
  • 26
  • 48