0

I'm attempting to create a function that sorts a list of players and identifies the top 5 by score.

I'm running a few chained filters on an array and I'd like to be able to use the current state of the modified array after each step.

I'm currently achieving this in two chain steps but I'd like to it in one if possible:

var hilightTop5 = function( propName, aPlayers ) {

   var aSortedReversed = _.chain(aPlayers)
        .sortBy( function(player){ return player[propName] })
        .reverse()
        .value();

    var aTop5Map = _.chain(aSortedReversed)
        .map( function(player) {  
            player.top5 = ( player[propName] >= aSortedReversed[4][propName] ) ? 0 : 1; 
            return player; })   
        .value();

    return aTop5Map;
};  

I'd like to do something like this and only use one chain:

    var hilightTop5 = function( propName, aPlayers ) {

       var aTop5Map = _.chain(aPlayers)
            .sortBy( function(player){ return player[propName] })
            .reverse()
            .map( function(player) {  
                var aCurrentStateTop5Map = aTop5Map.value(); // this.aTop5Map.value() ?!
                player.top5 = ( player[propName] >= aCurrentStateTop5Map[4][propName] ) ? 0 : 1; 
                return player; })   
            .value();


        return aTop5Map;
    }; 

Is that possible? To somehow use the state of the array after each filter step?

4

1 回答 1

1

您可以使用下划线传递给映射迭代器的列表值:

var hilightTop5 = function(sortProperty, players) {
    return _.chain(players)
        .sortBy(sortProperty)
        .reverse()
        .map(function(player, key, list) {
            player.top5 = (player[sortProperty] >= list[4][sortProperty]) ? 1 : 0;
            // Another possibility:
            // player.top5 = (key < 5) ? 1 : 0;
            return player;
        })
        .value();            
}
于 2013-11-14T15:51:23.737 回答