

- 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 object array based on another array of keys - 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. This will produce the following output −
const output = [{d:4},{a:1},{b:2},{c:3}];
Example
Following is the code −
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
This will produce the following output in console −
[ { d: 4 }, { a: 1 }, { b: 2 }, { c: 3 } ]
- Related Questions & Answers
- Sort array based on another array in JavaScript
- Sorting Array based on another array JavaScript
- Filter array based on another array in JavaScript
- Modify an array based on another array JavaScript
- Get range of months from array based on another array JavaScript
- Order an array of words based on another array of words JavaScript
- Creating an array of objects based on another array of objects JavaScript
- Sort array based on presence of fields in objects JavaScript
- Filter an object based on an array JavaScript
- Sort HashMap based on keys in Java
- Manipulate Object to group based on Array Object List in JavaScript
- Sort array based on min and max date in JavaScript?
- Filter an array containing objects based on another array containing objects in JavaScript
- JavaScript: replacing object keys with an array
- Sort an array according to another array in JavaScript
Advertisements