I'm trying to sort an array of objects based on a property value in that array. When I put a request to the API I'm using, this is what is returned to me.
0: {id: 23634, pollId: 6907, name: "B", type: "PollOption", totalAmountRaised: 341, …}
1: {id: 23635, pollId: 6907, name: "A", type: "PollOption", totalAmountRaised: 636, …}
2: {id: 23641, pollId: 6907, name: "C", type: "PollOption", totalAmountRaised: 246, …}
3: {id: 23642, pollId: 6907, name: "D", type: "PollOption", totalAmountRaised: 1092, …}
4: {id: 23643, pollId: 6907, name: "E", type: "PollOption", totalAmountRaised: 0, …}
I would like to sort the array by the value totalAmountRaised, from biggest to smallest. I am trying to use the sort() method to avoid writing a big complex function. This is what I'm looking for.
arrayToSort.sort((a, b) => (a.totalAmountRaised < b.totalAmountRaised) ? 1 : -1);
0: {id: 23642, pollId: 6907, name: "D", type: "PollOption", totalAmountRaised: 1092, …}
1: {id: 23635, pollId: 6907, name: "A", type: "PollOption", totalAmountRaised: 636, …}
2: {id: 23634, pollId: 6907, name: "B", type: "PollOption", totalAmountRaised: 341, …}
3: {id: 23641, pollId: 6907, name: "C", type: "PollOption", totalAmountRaised: 246, …}
4: {id: 23643, pollId: 6907, name: "E", type: "PollOption", totalAmountRaised: 0, …}
But, when I run the method, it only swaps the values of totalAmountRaised, it doesn't actually change the order of the array, which is what I'm looking for. This is what's actually returned.
0: {id: 23634, pollId: 6907, name: "B", type: "PollOption", totalAmountRaised: 1092, …}
1: {id: 23635, pollId: 6907, name: "A", type: "PollOption", totalAmountRaised: 636, …}
2: {id: 23641, pollId: 6907, name: "C", type: "PollOption", totalAmountRaised: 341, …}
3: {id: 23642, pollId: 6907, name: "D", type: "PollOption", totalAmountRaised: 246, …}
4: {id: 23643, pollId: 6907, name: "E", type: "PollOption", totalAmountRaised: 0, …}
Any help would be appreciated, thanks!