Sort array based on another array in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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' ]
raja
Published on 26-Aug-2020 14:30:18
Advertisements