- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Relative sorting in JavaScript
Suppose, we have two arrays, let’s say arr1 and arr2. The elements of arr2 are distinct, and all elements in arr2 are also in arr1.
We are required to write a JavaScript function that takes in two such arrays and sorts the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don't appear in arr2 should be placed at the end of arr1 in ascending order.
For example− If the two input arrays are −
const arr1 = [2,3,1,3,2,4,6,7,9,2,19]; const arr2 = [2,1,4,3,9,6];
Then the output should be −
const output = [2,2,2,1,4,3,3,9,6,7,19];
Example
const arr1 = [2,3,1,3,2,4,6,7,9,2,19]; const arr2 = [2,1,4,3,9,6]; const relativeSortArray = (arr1, arr2) => { const map = new Map(); const len = arr2.length; arr2.forEach((a, i) => { map.set(a, i); }); return arr1.sort((a, b) => { a = map.has(a) ? map.get(a) : len + a; b = map.has(b) ? map.get(b) : len + b; return a - b; }); }; console.log(relativeSortArray(arr1, arr2));
Output
And the output in the console will be −
[ 2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19 ]
- Related Articles
- Alphanumeric sorting using JavaScript
- Uneven sorting of array in JavaScript
- Sorting a JSON object in JavaScript
- Sorting string in reverse order in JavaScript
- Sorting Array with JavaScript reduce function - JavaScript
- Topological sorting using Javascript DFS
- JavaScript array sorting by level
- Sorting arrays by two criteria in JavaScript
- Alternative sorting of an array in JavaScript
- Special type of sorting algorithm in JavaScript
- Sorting string characters by frequency in JavaScript
- Sorting an array by date in JavaScript
- Sorting parts of array separately in JavaScript
- Sorting an array by price in JavaScript
- Sorting strings with decimal points in JavaScript

Advertisements