I have an array of objects like below, and I would like to sort the array by value of each object.
const arr = [
{
0: "id1",
1: {
title: "object1",
value: 200
}
},
{
0: "id2",
1: {
title: "object2",
value: 100
}
},
{
0: "id3",
1: {
title: "object3",
value: 300
}
},
]
//result - array I want to get as the final result of sort
sortedArr = [
{
0: "id3",
1: {
title: "object2",
value: 100
}
},
{
0: "id2",
1: {
title: "object1",
value: 200
}
},
{
0: "id3",
1: {
title: "object3",
value: 300
}
},
]
I tried:
const sortedArr = arr.sort((a, b) => {
if (a[1].value - b[1].value) {
return -1
} else {
return 1
}
})
But I only get the reversed array not sorted as I wish.
I found similar problems but when I tried other solutions it didn’t work for me, or I did something wrong.
2
Answers
You’re misusing data formats I think. Objects are not a replacement for Arrays where keys have to be indexed
0
,1
…Anyways:
A far better data input given a well structured array of items objects would be:
Interesing!
What do you think about my code:
const sortedArr = arr.sort((a, b) => a[1].value > b[1].value - 1);