 
 Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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' ]
Advertisements
                    