Sorting Array based on another array JavaScript


Suppose, we have two arrays like these −

const input = ['S-1','S-2','S-3','S-4','S-5','S-6','S-7','S-8'];
const sortingArray = ["S-1", "S-5", "S-2", "S-6", "S-3", "S-7", "S-4", "S-8"];

We are required to write a JavaScript function that takes in two such arrays as first and second argument respectively.

The function should sort the elements of the first array according to their position in the second array.

The code for this will be −

Example

const input = ['S-1','S-2','S-3','S-4','S-5','S-6','S-7','S-8'];
const sortingArray = ["S-1", "S-5", "S-2", "S-6", "S-3", "S-7", "S-4", "S-8"];
const sortByReference = (arr1 = [], arr2 = []) => {
   const sorter = (a, b) => {
      const firstIndex = arr2.indexOf(a);
      const secondIndex = arr2.indexOf(b);
      return firstIndex - secondIndex;
   };
   arr1.sort(sorter);
};
sortByReference(input, sortingArray); console.log(input);

Output

And the output in the console will be −

[
'S-1',
'S-5',
'S-2',
'S-6',
'S-3',
'S-7',
'S-4',
'S-8'
]

Updated on: 21-Nov-2020

269 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements