Sorting Array with Standard Values in 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'];
Example
Following is the code −
const dbArray = ['Apple','Banana','Mango','Apple','Mango','Mango','Apple']; const stdArray = ['Mango','Apple','Banana','Grapes']; const sortByRef = (arr, ref) => { const sorter = (a, b) => { return ref.indexOf(a) - ref.indexOf(b); }; arr.sort(sorter); }; sortByRef(dbArray, stdArray); console.log(dbArray);
Output
Following is the output in the console −
[ 'Mango', 'Mango', 'Mango', 'Apple', 'Apple', 'Apple', 'Banana' ]
Advertisements