Sort an array according to another array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have two arrays of literals like these −

const arr1 = [1, 3, 2, 4, 5, 6];
const arr2 = [1, 2, 5];

We are required to write a JavaScript function that takes in two such arrays. Then our function should return a new array that contains all the elements of arr1 but sorted according to arr2.

Like the elements that appear in both the array should appear first according to their order in the second array followed by the elements only present in first array retaining their order.

Example

The code for this will be −

const arr1 = [1, 3, 2, 4, 5, 6];
const arr2 = [1, 2, 5];
const sortByReference = (arr1, arr2) => {
   const inBoth = el => arr1.indexOf(el) !== -1 && arr2.indexOf(el) !== -1;
   const sorter = (a, b) => {
      if(inBoth(a) && inBoth(b)){
         return arr1.indexOf(a) - arr2.indexOf(b);
      }
      if(inBoth(a)){
         return -1;
      };
      if(inBoth(b)){
         return 1;
      };
      return 0;
   };
   arr1.sort(sorter);
};
sortByReference(arr1, arr2);
console.log(arr1);

Output

The output in the console −

[ 1, 2, 5, 3, 4, 6 ]
raja
Published on 12-Oct-2020 11:22:00
Advertisements