- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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' ]
- Related Articles
- Sorting an array of binary values - JavaScript
- Sorting an array of objects by property values - JavaScript
- Sorting an array of objects by an array JavaScript
- Sorting Array with JavaScript reduce function - JavaScript
- Alternative sorting of an array in JavaScript
- Sorting an array by date in JavaScript
- Sorting an array by price in JavaScript
- Sorting an associative array in ascending order - JavaScript
- Sorting only a part of an array JavaScript
- Sorting an array that contains undefined in JavaScript?
- Sorting Array based on another array JavaScript
- Mapping an array to a new array with default values in JavaScript
- JavaScript array sorting by level
- JavaScript - filtering array with an array
- PHP program to find standard deviation of values within an array

Advertisements