返回具有最高价值的对象 [英] Return object with highest value

查看:40
本文介绍了返回具有最高价值的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a array called games with a 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的方法,但是它返回的是投票数,而不是对象本身.

I want to return the object with the most amount of votes. I've googled and found some methods using Math.max.apply, but it's returning the number of votes, and not the object itself.

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

任何有关如何归还票数最高的对象的提示吗?

Any tips on how to return the object with the highest votes?

推荐答案

您可以做一个简单的单行

You can do a simple one-line reduce:

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

这篇关于返回具有最高价值的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆