gpt4 book ai didi

javascript - 如何跳过相同的值并获取数组长度

转载 作者:行者123 更新时间:2023-11-29 10:08:15 25 4
gpt4 key购买 nike

我有我的示例数组:

var person = [{
firstName:"John",
lastName:"Doe",
age:46
},
{
firstName:"Alexander",
lastName:"Bru",
age:46
},
{
firstName:"Alex",
lastName:"Bruce",
age:26
}];

简单 person.length 给我数组的长度,但我需要在年龄相同时合并值。因此,如果两个人的年龄相同,则返回 1 而非 2。抱歉我的英语不好,我可能会犯错误。

最佳答案

使用 Array#forEach 带有年龄对象引用的方法。

var person = [{
firstName: "John",
lastName: "Doe",
age: 46
}, {
firstName: "Alexander",
lastName: "Bru",
age: 46
}, {
firstName: "Alex",
lastName: "Bruce",
age: 26
}];
// object for storing reference to age
var obj = {},
res = 0;
// iterate and count
person.forEach(function(v) {
// check age already not defined
if (!obj[v.age]) {
// define the property
obj[v.age] = true;
// increment count
res++;
}
});

console.log(res);

关于javascript - 如何跳过相同的值并获取数组长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38924617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com