返回具有最高值的对象

时间:2016-04-29 14:36:41

标签: javascript

我有一个名为游戏的数组,其值为votes

let games = [
    { id: 1, name: 'Star Wars: Imperial Assault', company: company.Fantasy_Flight, available: true, category: Category.SciFi, votes: 3},
    { id: 2, name: 'Game of Thrones: Second Edition', company: 'Fantassy Flight', available: false, category: Category.Fantasy, votes: 4 },
    { id: 3, name: 'Merchans and Marauders', company: 'Z-Man Gaming', available: true, category: Category.Pirates, votes: 5 },
    { id: 4, name: 'Eclipse', company: 'Lautapelit', available: false, category: Category.SciFi, votes: 6 },
    { id: 5, name: 'Fure of Dracula', company: 'Fantasy Flight', available: true, category: Category.Fantasy, votes: 2 }
]

我想以最多的票数返回该对象。我用google搜索并找到了一些使用Math.max.apply的方法,但它返回的是投票数,而不是对象本身。

function selectMostPopular():string {
    const allGames = getAllGames();
    let mostPopular: string = Math.max.apply(Math, allGames.map(function (o) { return o.votes; }));
    console.log(mostPopular);
    return mostPopular;
};

有关如何以最高票数退回对象的任何提示?

4 个答案:

答案 0 :(得分:9)

你可以做一个简单的单行reduce

let maxGame = games.reduce((max, game) => max.votes > game.votes ? max : game);

答案 1 :(得分:1)

您可以使用Array#mapArray#find

// First, get the max vote from the array of objects
var maxVotes = Math.max(...games.map(e => e.votes));

// Get the object having votes as max votes
var obj = games.find(game => game.votes === maxVotes);

(function () {
    var games = [{
        id: 1,
        name: 'Star Wars: Imperial Assault',
        company: 'company.Fantasy_Flight',
        available: true,
        category: 'Category.SciFi',
        votes: 3
    }, {
        id: 2,
        name: 'Game of Thrones: Second Edition',
        company: 'Fantassy Flight',
        available: false,
        category: 'Category.Fantasy',
        votes: 4
    }, {
        id: 3,
        name: 'Merchans and Marauders',
        company: 'Z-Man Gaming',
        available: true,
        category: 'Category.Pirates',
        votes: 5
    }, {
        id: 4,
        name: 'Eclipse',
        company: 'Lautapelit',
        available: false,
        category: 'Category.SciFi',
        votes: 6
    }, {
        id: 5,
        name: 'Fure of Dracula',
        company: 'Fantasy Flight',
        available: true,
        category: 'Category.Fantasy',
        votes: 2
    }];

    var maxVotes = Math.max(...games.map(e => e.votes));
    var obj = games.find(game => game.votes === maxVotes);
    console.log(obj);

    document.body.innerHTML = '<pre>' + JSON.stringify(obj, 0, 4);
}());

答案 2 :(得分:1)

当您找到更大的值时,只需迭代,更新最大值和找到它的对象:

var max = -Infinity, argmax;
for(var game of games)
  if(game.votes >= max)
    max = game.votes, argmax = game;
argmax;

答案 3 :(得分:0)

根据投票数排序怎么样?

games.sort( function(a, b){
    return a.votes < b.votes; 
}); 

现在阵列中的第一个游戏票数最多。