gpt4 book ai didi

javascript - 如何使用reduce函数有效地评估javascript数组中的元素

转载 作者:行者123 更新时间:2023-11-30 07:30:26 25 4
gpt4 key购买 nike

我有一个名为people 的数组,它是一个对象数组(人的 名字和他/她的城市 的名字),以及我想制作一个函数来计算该数组中不同城市的总数。我使用了一个使用 for 循环的函数,但在 javascript 中使用 reduce 函数似乎是更好的方法。这是片段

const people = [
{ name: "Jessica", city: "New York"},
{ name: "Steve", city: "Los Angels"},
{ name: "Peter", city: "Boston"},
{ name: "Elaine", city: "Montreal"},
{ name: "Chris", city: "Montreal"},
{ name: "Mike", city: "Boston"},
{ name: "George", city: "Vancouver"},
];
let nbre_distinct_cities = 0;

countDistinctCity(people);
console.log('Total number of distinct cities: ',nbre_distinct_cities);

function countDistinctCity(people)
{
for(let i = 0; i < people.length; i++)
{
if(i === people.length - 1)
{
break;
}
else if(people[i].city !== people[i + 1].city)
{
nbre_distinct_cities++
}
}

}

如果有人建议使用 reduce() 函数的高效函数,我将不胜感激

最佳答案

您可以使用 Set存储数组中的所有城市,并且由于集合只有唯一条目,集合的最终大小将为您提供不同城市的数量:

const people = [
{ name: "Jessica", city: "New York"},
{ name: "Steve", city: "Los Angels"},
{ name: "Peter", city: "Boston"},
{ name: "Elaine", city: "Montreal"},
{ name: "Chris", city: "Montreal"},
{ name: "Mike", city: "Boston"},
{ name: "George", city: "Vancouver"},
];

let nbre_distinct_cities = new Set(people.map(({city}) => city)).size;
console.log('Total number of distinct cities: ', nbre_distinct_cities);

关于javascript - 如何使用reduce函数有效地评估javascript数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57293971/

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