如何在对象数组中找到最长的数组? [英] How to find longest length array within an array of an object?

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

问题描述

我试图提出一个函数,该函数返回数组中长度最长的对象.

I am trying to come up with a single function that returns the object with the longest length array within an array.

这是问题:

  1. 编写一个列出所有武器最多的兽人的函数.

示例:

var orcs = [{
    name: 'Orgoth',
    strength: 9001,
    weapons: ['Bone ax', 'Mace of Strength']
}, {
    name: 'Blaroguhh',
    strength: 500,
    weapons: ['Cheeseburger', 'Spear of the Hut']
}, {
    name: 'Mark',
    strength: 543,
    weapons: ['Ax of Defense', 'Dagger', 'Sword']
}]
getMostWeapons(orcs);
// =>   {name: 'Mark', strength: 543, weapons: ['Ax of Defense', 'Dagger', 'Sword' ]}

这是我到目前为止所拥有的:

And this is what I have so far:

function getMostWeapons(orcs) {
    var length = 0;
    return orcs.filter(function (obj) {
        return obj.filter(function (val) {
            if (val.length > length) {
                return (length = val.length);
            }
        });
    });
}

推荐答案

.filter用于返回所有符合条件的数组元素.由于直到遍历所有兽人后才知道最大长度,因此无法一口气使用它来找到要返回的兽人.

.filter is used to return all the array elements that match a criteria. Since you don't know the maximum length until you've gone through all the orcs, you can't use it in one pass to find the orc to return.

只需使用一个普通的循环,将武器的长度与迄今为止所见的最长长度进行比较即可.如果更长,请用这个替换最长的一个.

Just use an ordinary loop that compares the length of weapons to the longest seen so far. If it's longer, replace the longest with this one.

function getMostWeapons(orcs) {
    var longest = 0;
    var longestOrcs = [];
    orcs.forEach(function(orc) {
        if (orc.weapons.length > longest) {
            longestOrcs = [orc];
            longest = orc.weapons.length;
        } else if (orc.weapons.length == longest) {
            longestOrcs.push(orc);
        }
    });
    return longestOrcs;
}

这篇关于如何在对象数组中找到最长的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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