
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 by index of an array in JavaScript
Suppose we have the following array of objects −
const arr = [ { 'name' : 'd', 'index' : 3 }, { 'name' : 'c', 'index' : 2 }, { 'name' : 'a', 'index' : 0 }, { 'name' : 'b', 'index' : 1 } ];
We are required to write a JavaScript function that takes in one such array.
The function should sort this array in increasing order according to the index property of objects.
Then the function should map the sorted array to an array of strings where each string is the corresponding name property value of the object.
Therefore, for the above array, the final output should look like −
const output = ["a", "b", "c", "d"];
Example
The code for this will be −
const arr = [ { 'name' : 'd', 'index' : 3 }, { 'name' : 'c', 'index' : 2 }, { 'name' : 'a', 'index' : 0 }, { 'name' : 'b', 'index' : 1 } ]; const sortAndMap = (arr = []) => { const copy = arr.slice(); const sorter = (a, b) => { return a['index'] - b['index']; }; copy.sort(sorter); const res = copy.map(({name, index}) => { return name; }); return res; }; console.log(sortAndMap(arr));
Output
And the output in the console will be −
[ 'a', 'b', 'c', 'd' ]
Advertisements