Sort the second array according to the elements of the first array in JavaScript



Suppose, we have two arrays like these βˆ’

const arr1 = ['d','a','b','c'] ;
const arr2 = [{a:1},{c:3},{d:4},{b:2}];

We are required to write a JavaScript function that accepts these two arrays. The function should sort the second array according to the elements of the first array.

We have to sort the keys of the second array according to the elements of the first array.

Therefore, the output should look like βˆ’

const output = [{d:4},{a:1},{b:2},{c:3}];

Therefore, let’s write the code for this function βˆ’

Example

The code for this will be βˆ’

const arr1 = ['d','a','b','c'] ;
const arr2 = [{a:1},{c:3},{d:4},{b:2}];
const sortArray = (arr1, arr2) => {
   arr2.sort((a, b) => {
      const aKey = Object.keys(a)[0];
      const bKey = Object.keys(b)[0];
      return arr1.indexOf(aKey) - arr1.indexOf(bKey);
   });
};
sortArray(arr1, arr2);
console.log(arr2);

Output

The output in the console will be βˆ’

[ { d: 4 }, { a: 1 }, { b: 2 }, { c: 3 } ]
Updated on: 2020-10-21T12:04:17+05:30

220 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements