Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
82
rated 0 times [  88] [ 6]  / answers: 1 / hits: 29056  / 7 Years ago, wed, may 31, 2017, 12:00:00

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.


More From » arrays

 Answers
13

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)




[#57607] Sunday, May 28, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
charisma

Total Points: 1
Total Questions: 99
Total Answers: 117

Location: Thailand
Member since Thu, Apr 22, 2021
3 Years ago
;