- Trending Categories
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
Sort an array according to another array in JavaScript
Suppose we have two arrays of literals like these −
const arr1 = [1, 3, 2, 4, 5, 6]; const arr2 = [1, 2, 5];
We are required to write a JavaScript function that takes in two such arrays. Then our function should return a new array that contains all the elements of arr1 but sorted according to arr2.
Like the elements that appear in both the array should appear first according to their order in the second array followed by the elements only present in first array retaining their order.
Example
The code for this will be −
const arr1 = [1, 3, 2, 4, 5, 6]; const arr2 = [1, 2, 5]; const sortByReference = (arr1, arr2) => { const inBoth = el => arr1.indexOf(el) !== -1 && arr2.indexOf(el) !== -1; const sorter = (a, b) => { if(inBoth(a) && inBoth(b)){ return arr1.indexOf(a) - arr2.indexOf(b); } if(inBoth(a)){ return -1; }; if(inBoth(b)){ return 1; }; return 0; }; arr1.sort(sorter); }; sortByReference(arr1, arr2); console.log(arr1);
Output
The output in the console −
[ 1, 2, 5, 3, 4, 6 ]
Advertisements