# Relative sorting in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
]
Published on 21-Nov-2020 06:42:22

Advertisements