Sorting or Arranging an Array with standard array values - JavaScript

We are required to sort a dynamic JavaScript array. The condition is that we are required to sort it according to the values stored in a particular order in a standard predefined array.

Let’s say the following is our dynamic array −

const dbArray = ['Apple','Banana','Mango','Apple','Mango','Mango','Apple'];

And suppose the standard array against which we have to sort the above array is like −

const stdArray = ['Mango','Apple','Banana','Grapes'];

So, after sorting the dbArray, my resultant array should look like −

const resultArray = ['Mango','Mango','Mango','Apple','Apple','Apple','Banana'];


Following is the code −

const dbArray =
const stdArray = ['Mango','Apple','Banana','Grapes'];
const sortByRef = (arr, ref) => {
   const sorter = (a, b) => {
      return ref.indexOf(a) - ref.indexOf(b);
sortByRef(dbArray, stdArray);


Following is the output in the console −

   'Mango',  'Mango',
   'Mango',  'Apple',
   'Apple',  'Apple',

Updated on: 18-Sep-2020


Kickstart Your Career

Get certified by completing the course

Get Started