- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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'];
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