0

I have an array of data that queries the results through a prop. I am able to obtain the data but, unable to sort it. I want all the data with MyTeam to appear first.

However, when I load this into the browser I obtain different results.

In Safari the data lists MyTeam to be the second element in the array

In Chrome, the data lists MyTeam to be the third element but, whenever I interact with them (via an onClick method) the data swaps around in a different order.

If I don't have the .sort() method, everything remains the same and nothing changes.

Is there a proper way to sort the array?

    var gameList = this.props.data.sort(function(game) {
        return (game.homeTeam == 'MyTeam' || game.awayTeam == 'MyTeam') ? 0 : 1;
    }).map(function(game, i) {
       //console.log(game.homeTeam + ' ' + game.awayTeam);
       });

1 Answer 1

1

Array#sort compares TWO items of the array. Your compare function must have two arguments. I suggest the following:

var gameList = this.props.data.sort(function(a, b) {
    var matchA = a.homeTeam === 'MyTeam' || a.awayTeam === 'MyTeam';
    var matchB = b.homeTeam === 'MyTeam' || b.awayTeam === 'MyTeam';

    // This will return
    // -1 if matchA is true and matchB is false
    //  0 if matchA and matchB are both true or both false
    //  1 if matchA is false and matchB is true
    return (matchB ? 1 : 0) - (matchA ? 1 : 0);
});
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for clarifying this seems to place MyTeam first now and is stable in Safari. The results still seem a bit wonky though in Chrome and keep jumping around (with MyTeam staying as the first result)
Well sort isn't guaranteed to be stable. The order of a and b is arbitrary if the compare function returns 0.
Thanks @David Is there no stable method at the moment to sort through the arrays?
If you want a particular order, you'll need to choose something else to sort on. Suppose each has a unique numeric id. You could change it to: return (matchB ? 1 : 0) - (matchA ? 1 : 0) || b.id - a.id;

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.