如何在对象数组中找到最长的数组?

问题描述:

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

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