
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 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 ]
- Related Questions & Answers
- Sort an array according to the order defined by another array in C++
- How to sort array according to age in JavaScript?
- Sort array based on another array in JavaScript
- Sorting an array according to another array using pair in STL in C++
- Sort an array of strings according to string lengths in C++
- Sort an array according to count of set bits in C++
- Sort the second array according to the elements of the first array in JavaScript
- Sort array according to the date property of the objects JavaScript
- Sort object array based on another array of keys - JavaScript
- Sort the array of strings according to alphabetical order defined by another string in C++
- Modify an array based on another array JavaScript
- JavaScript in filter an associative array with another array
- Using merge sort to recursive sort an array JavaScript
- How to extend an existing JavaScript array with another array?
- Sort nested array containing objects ascending and descending according to date in JavaScript
Advertisements