

- 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
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 } ]
- Related Questions & Answers
- Sort array according to the date property of the objects JavaScript
- Difference between first and the second array in JavaScript
- Sort an array according to another array in JavaScript
- Subtracting array in JavaScript Delete all those elements from the first array that are also included in the second array
- Set the first array elements raised to powers from second array element-wise in Numpy
- Sort an array to have specific items first in the array - JavaScript
- Return the bases when first array elements are raised to powers from second array in Python
- How to sort array according to age in JavaScript?
- Sort an array according to the order defined by another array in C++
- Maximize first array over second in JavaScript
- Find the first, second and third minimum elements in an array in C++
- Python program to sort a list according to the second element in the sublist.
- Sorting array according to increasing frequency of elements in JavaScript
- Sort a list according to the Length of the Elements in Python program
- Python program to sort a List according to the Length of the Elements?
Advertisements