簡體   English   中英

返回具有最高值的對象

[英]Return object with highest value

我有一個名為游戲的數組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;
};

關於如何以最高票數返回對象的任何提示?

你可以做一個簡單的單線reduce

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

您可以使用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); }()); 

只需迭代,更新最大值,並在找到更大的值時找到它的對象:

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

如何根據投票數進行排序?

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

現在陣列中的第一個游戲票數最多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM