Sort array based on another array in JavaScript


We are required to write a sorting function that sort an array based on the contents of another array.

For example − We have to sort the original array such that the elements present in the below sortOrder array appear right at the start of original array and all other should keep their order −

const originalArray = ['Apple', 'Cat', 'Fan', 'Goat', 'Van', 'Zebra'];
const sortOrder = ['Zebra', 'Van'];

Example

const originalArray = ['Apple', 'Cat', 'Fan', 'Goat', 'Van', 'Zebra'];
const sortOrder = ['Zebra', 'Van'];
const sorter = (a, b) => {
   if(sortOrder.includes(a)){
      return -1;
   };
   if(sortOrder.includes(b)){
      return 1;
   };
   return 0;
};
originalArray.sort(sorter);
console.log(originalArray);

Output

The output in the console will be −

[ 'Zebra', 'Van', 'Apple', 'Cat', 'Fan', 'Goat' ]

Updated on: 26-Aug-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements