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!

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

3 Comments

Yeah, thank you! - Can you explain why? I don't get why you have to write b.votes - a.votes
Yeah, there is a good explanation here: stackoverflow.com/questions/6567941/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.