简体   繁体   中英

ReactJS using .sort() method mixing up results in array

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);
       });

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM