查找数组中具有最高属性值的对象索引 [英] Find index of object in array with highest value in property

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

问题描述

我有一个包含对象的数组:

I've got an array with objects:

var articles = [];
var article = {};

Simple loop that iterates x times {
        article.text = "foobar";
        article.color = "red";
        article.number = 5;
        articles.push(article);
}

我不知道我的数组中有多少个对象,但它们的属性值都不同,我只是在这里举了一些例子.

I have no idea how many objects there will be in my array but they will all have different values for their properties, I just gave some examples here.

问题

我需要找到一种方法来遍历所有这些对象并检索 article.number 中具有最高值的对象的索引.我怎样才能做到这一点?我可能只使用 javascript、jQuery 等.没有其他语言.

I need to find a way to go through all these objects and retrieve the index of the object that has the highest value in article.number. How can I achieve this? I may only use javascript, jQuery, etc.. no other languages.

我猜这将涉及同时使用 $.grep 和 Math.max 但我被卡住了,我以前从未使用过 $.grep.

I'm guessing this will involve using both $.grep and Math.max but I'm stuck, I've never worked with $.grep before.

简而言之:

var highestNumber = index of object where article.number is highest

推荐答案

有很多方法可以做到这一点,Math.max()$.grep$.map 是少数,但一个简单易读的应该可以理解的方法是迭代对象,并检查值是否高于变量,如果是,则将变量设置为更高的数字:

There are many ways to do this, Math.max(), $.grep and $.map being a few, but an easy and readable method that should be understandable is to just iterate the object, and check if the value is higher than a variable, if it is, set the variable to the higher number :

var highest = 0;

$.each(articles, function(key, article) {

    if (article.number > highest) highest = article.number;

});

// highest now contains the highest number

这篇关于查找数组中具有最高属性值的对象索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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