0

I would like to sort my array by a value which is contained inside the array of the array. This is my array which I fetch from an API:

0: {id: 1126, votes: 2}
1: {id: 1125, votes: 4}
2: {id: 1124, votes: 0}
3: {id: 1123, votes: 1}
...

So, on index 0 I have an array which has the id 1126 and contains the variable votes 2. Now I want to order the array by the votes amount.

This is how far I got (It returns the same array...):

data = [].concat(data).sort((a, b) => a.votes > b.votes);

However, I don't get the result I want to have. I want to have it ordered by votes. Like this:

0: {id: 1125, votes: 4}
1: {id: 1126, votes: 2}
2: {id: 1123, votes: 1}
3: {id: 1124, votes: 0}
...

I would appreciate any kind of help! Kind regards and Thank You!

Jan
  • 1,180
  • 3
  • 23
  • 60

1 Answers1

2
const arr = [{id: 1126, votes: 2},{id: 1125, votes: 4},{id: 1124, votes: 0}]

arr.sort((a,b) => b.votes - a.votes)

That will result in:

0: {id: 1125, votes: 4}
1: {id: 1126, votes: 2}
2: {id: 1124, votes: 0}

Does that help you?

  • Yeah, thank you! - Can you explain why? I don't get why you have to write `b.votes - a.votes` – Jan Jan 06 '19 at 13:02
  • [Array.prototype.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) – pishpish Jan 06 '19 at 13:06
  • Yeah, there is a good explanation here: https://stackoverflow.com/questions/6567941/how-does-sort-function-work-in-javascript-along-with-compare-function – Michiel de Vos Jan 06 '19 at 13:07