我有一个名为带有值的游戏数组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 }
]
Run Code Online (Sandbox Code Playgroud)
我想以最多的票数返回该对象.我用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;
};
Run Code Online (Sandbox Code Playgroud)
关于如何以最高票数返回对象的任何提示?
and*_*dyk 13
你可以做一个简单的单行reduce:
let maxGame = games.reduce((max, game) => max.votes > game.votes ? max : game);
Run Code Online (Sandbox Code Playgroud)
Tus*_*har 10
您可以使用Array#map和Array#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);
Run Code Online (Sandbox Code Playgroud)
// 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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1757 次 |
| 最近记录: |