繁体   English   中英

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

[英]How to efficiently evaluate element in javascript array by using reduce function

我有一个名为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); 

使用减少

Object.keys(people.reduce((acc, ppl) => (acc[ppl.city] = ppl.city, acc), {})).length

你可以通过减少方法解决问题

    const cities = people.reduce((accumulator, current) => {
       const isItNotExistInAccumulator
          = accumulator.every(city => city !== current.city);
       if (isItNotExistInAccumulator) return [current.city, ...accumulator];
       return accumulator;
    }, []);

    console.log(cities.length);

一种替代解决方案,使用Array.indexOf删除重复Array.indexOf

 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 = people.map(el => el.city) .filter((city, idx, arr) => arr.indexOf(city) === idx).length; console.log('Total number of distinct cities: ', nbre_distinct_cities); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM