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.