0

I am trying to sort an object so that the property with the most votes comes first. Here's my data structure enter image description here

I have found some articles on how to do this and I have created a new array and am pushing the votes value into it as well as the player object. The problem I am having is then sorting the options by the number, and removing the votes count from the array. Here's my code

    var sortedOptions = [];
    for (let option of options) {
        sortedOptions.push(option, option.votes);
    }

    sortedOptions.sort(function(a, b) {

    })

I have been following this but I don't understand how the sort function is working and how to do it for my purposes.

Thanks for your help :)

EDIT: I tried doing the following code, however this was returning an object with 8 options and the object isn't sorted

    sortedOptions.sort(function(a, b) {
        return a.votes - b.votes;
    })

Resulted in enter image description here

jSutcliffe90
  • 323
  • 2
  • 5
  • 19

1 Answers1

3

You can use Array.prototype.sort()

The sort function takes a function as an argument, which compares two elements of the array to determine which one should be sorted where.

For your case where you want to sort based on votes you write it like so:

options.sort(function(a, b) {
    // use b - a to sort descending, a - b to sort ascending
    return b.votes - a.votes;
})

The for-loop you are using is strange: it produces an array which is mixed of objects and numbers, that's why the sort function doesn't work on it. Either sort on options directly, or if you need a copy use let sortedOptions = JSON.parse(JSON.stringify(options));

Danmoreng
  • 2,367
  • 1
  • 19
  • 32
  • Thanks for your answer mate. I just tried giving that a go, it sortedOptions with 8 values instead of 4 (because it hasn't removed the votes which were previously inserted) and they also aren't sorted which was the problem I was previously having. I have edited the question with a screenshot to better explain what I mean – jSutcliffe90 Oct 30 '17 at 14:38
  • You can also sort directly on the `options` array. the for-loop was irritating me but I thought you wanted to sort on a copy of the original array only. In your loop you add the votes and the object containing the votes both to the array - and therfor the sort function doesn't work as well. – Danmoreng Oct 30 '17 at 14:40
  • I just did it with the answer that you gave, I sorted it directly from the options array. I think I was just getting into a muddle following the article that I linked to by adding the votes totals into sortedOptions. I didn't need to do that and so just followed your answer. Cheers, all the best – jSutcliffe90 Oct 30 '17 at 15:11