![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
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' ]
Advertisements