Sort by index of an array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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' ]
raja
Published on 24-Nov-2020 10:55:17
Advertisements