Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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'];
How It Works
The solution uses Array.sort() with a custom comparator function. The comparator uses indexOf() to find each element's position in the standard array, then subtracts these positions to determine sort order.
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' ]
Alternative Approach
You can also create a reusable function that returns a sorted copy without modifying the original array:
const dbArray = ['Apple','Banana','Mango','Apple','Mango','Mango','Apple'];
const stdArray = ['Mango','Apple','Banana','Grapes'];
const getSortedArray = (arr, ref) => {
return [...arr].sort((a, b) => ref.indexOf(a) - ref.indexOf(b));
};
const sortedArray = getSortedArray(dbArray, stdArray);
console.log('Original:', dbArray);
console.log('Sorted:', sortedArray);
Original: [ 'Apple', 'Banana', 'Mango', 'Apple', 'Mango', 'Mango', 'Apple' ] Sorted: [ 'Mango', 'Mango', 'Mango', 'Apple', 'Apple', 'Apple', 'Banana' ]
Key Points
? Elements not found in the standard array will have indexOf() return -1, placing them at the beginning
? The original array is modified when using sort() directly
? Use spread operator [...arr] to create a copy if you want to preserve the original
Conclusion
This technique allows you to sort arrays based on a predefined order using indexOf() with a custom comparator. It's useful for organizing data according to business rules or user preferences.
