
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort Array Based on Another Array in JavaScript
We are required to write a sorting function that sort an array based on the contents of another array.
For example − We have to sort the original array such that the elements present in the below sortOrder array appear right at the start of original array and all other should keep their order −
const originalArray = ['Apple', 'Cat', 'Fan', 'Goat', 'Van', 'Zebra']; const sortOrder = ['Zebra', 'Van'];
Example
const originalArray = ['Apple', 'Cat', 'Fan', 'Goat', 'Van', 'Zebra']; const sortOrder = ['Zebra', 'Van']; const sorter = (a, b) => { if(sortOrder.includes(a)){ return -1; }; if(sortOrder.includes(b)){ return 1; }; return 0; }; originalArray.sort(sorter); console.log(originalArray);
Output
The output in the console will be −
[ 'Zebra', 'Van', 'Apple', 'Cat', 'Fan', 'Goat' ]
Advertisements