

- 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
Sorting Array based on another array JavaScript
Suppose, we have two arrays like these −
const input = ['S-1','S-2','S-3','S-4','S-5','S-6','S-7','S-8']; const sortingArray = ["S-1", "S-5", "S-2", "S-6", "S-3", "S-7", "S-4", "S-8"];
We are required to write a JavaScript function that takes in two such arrays as first and second argument respectively.
The function should sort the elements of the first array according to their position in the second array.
The code for this will be −
Example
const input = ['S-1','S-2','S-3','S-4','S-5','S-6','S-7','S-8']; const sortingArray = ["S-1", "S-5", "S-2", "S-6", "S-3", "S-7", "S-4", "S-8"]; const sortByReference = (arr1 = [], arr2 = []) => { const sorter = (a, b) => { const firstIndex = arr2.indexOf(a); const secondIndex = arr2.indexOf(b); return firstIndex - secondIndex; }; arr1.sort(sorter); }; sortByReference(input, sortingArray); console.log(input);
Output
And the output in the console will be −
[ 'S-1', 'S-5', 'S-2', 'S-6', 'S-3', 'S-7', 'S-4', 'S-8' ]
- Related Questions & Answers
- Sort array based on another array in JavaScript
- Filter array based on another array in JavaScript
- Modify an array based on another array JavaScript
- Sort object array based on another array of keys - JavaScript
- Get range of months from array based on another array JavaScript
- Sorting array based on increasing frequency of elements in JavaScript
- Order an array of words based on another array of words JavaScript
- Creating an array of objects based on another array of objects JavaScript
- Filter an array containing objects based on another array containing objects in JavaScript
- Reorder array based on condition in JavaScript?
- Build maximum array based on a 2-D array - JavaScript
- Sorting Array Elements in Javascript
- JavaScript array sorting by level
- Filter an object based on an array JavaScript
- Search and update array based on key JavaScript
Advertisements