我正在尝试获取元素数量最多的对象并获取元素数量。
我目前有以下内容:
var array = [
[{
'id': 1,
'value': 100
}, {
'id': 1,
'value': 100
}],
[{
'id': 1,
'value': 100
}, {
'id': 1,
'value': 100
}, {
'id': 1,
'value': 100
}],
[{
'id': 1,
'value': 100
}, {
'id': 1,
'value': 100
}]
];
for (var i = 0; i < array.length; i++) {
console.log(array[i].length);
//Here I need to get the bigger number in this case is 3, because I need it to another validations inside this for loop
}
在这种情况下,我知道更大的对象是什么,但我需要获取数字并将其保存在变量中,因为之后我需要进行一些验证。
希望您能理解我并帮助我
最佳答案
您可以使用reduce
获取最大的子数组(及其长度):
var array = [
[{
'id': 1,
'value': 100
},
{
'id': 1,
'value': 100
}
],
[{
'id': 1,
'value': 100
},
{
'id': 1,
'value': 100
},
{
'id': 1,
'value': 100
}
],
[{
'id': 1,
'value': 100
},
{
'id': 1,
'value': 100
}
]
];
var largest = array.reduce((a, c) => a.length < c.length ? c : a);
console.log(largest);
console.log(largest.length);
关于javascript - 获取元素个数最多的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53286385/