3

Look at the code below:

    var exemples =  [
            {
                'name'     : 'd',
                'index'    : 3
            },
            {
                'name'     : 'c',
                'index'     : 2
            },
            {
                'name'     : 'a',
                'index'    : 0
            },
            {
                'name'     : 'b',
                'index'    : 1
            }
        ];

      const list = exemples.map((exemple, index, array) => exemple.name)

      console.log(list)

it gives me that array:

["d", "c", "a", "b"]

I would like to respect the index and get a result like that:

["a", "b", "c", "d"]

Sounds like a basic question but I need your help. Thanks.

Pierre Trzaska
  • 105
  • 1
  • 3
  • 9

3 Answers3

7

Sort the list first, by a custom sort function which will compare the indices, and then map.

    var exemples =  [
            {
                'name'     : 'd',
                'index'    : 3
            },
            {
                'name'     : 'c',
                'index'     : 2
            },
            {
                'name'     : 'a',
                'index'    : 0
            },
            {
                'name'     : 'b',
                'index'    : 1
            }
        ];

      const list = exemples.sort((a,b) => a.index - b.index).map((exemple, index, array) => exemple.name)

      console.log(list)
Bernd Strehl
  • 2,852
  • 4
  • 24
  • 43
5

You don't need to sort and filter. Use Array#reduce. In just one iteration you can get the sorted elements. This is more efficient than first sorting and then filtering. This would give you O(n) solution. See below as an example.

var exemples = [{
    'name': 'd',
    'index': 3
  },
  {
    'name': 'c',
    'index': 2
  },
  {
    'name': 'a',
    'index': 0
  },
  {
    'name': 'b',
    'index': 1
  }
];

var ans = exemples.reduce(function (r,v) {
  r[v.index] = v.name;
  return r;
}, []);

console.log(ans);
Pankaj Shukla
  • 2,657
  • 2
  • 11
  • 18
1

You can sort the array before you map it. Here is an example:

var exemples =  [{'name'     : 'd','index'    : 3},{'name'     : 'c','index'     : 2},{'name'     : 'a','index'    : 0},{'name'     : 'b','index'    : 1}];

const list = exemples.sort((v1, v2) => v1.index - v2.index).map((v) => v.name);
console.log(list)
Titus
  • 22,031
  • 1
  • 23
  • 33