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

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

问题描述

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

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天全站免登陆