

- 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
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 Questions & Answers
- Sorting Array Elements in Javascript
- Alphanumeric sorting using JavaScript
- Sorting a JSON object in JavaScript
- Uneven sorting of array in JavaScript
- Topological sorting using Javascript DFS
- JavaScript array sorting by level
- Sorting Array with JavaScript reduce function - JavaScript
- Sorting string in reverse order in JavaScript
- Sorting arrays by two criteria in JavaScript
- Sorting arrays using bubble sort in JavaScript
- Sorting the numbers from within in JavaScript
- Sorting Array without using sort() in JavaScript
- Sorting an array by date in JavaScript
- Sorting parts of array separately in JavaScript
- Sorting an array by price in JavaScript
Advertisements