Wednesday, July 25, 2018

javascript - Sort by index an array




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.


Answer



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)




No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...