I have an array called people which is an array of objects(person's name and his/her city's name), and i want to make a function that calculate the total number of distinct cities in that array. I used a function that use for loop but it seems to be a better way by using reduce functions in javascript. Here is the snippet
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++
}
}
}
I would appreciate if someone suggest an efficient function using reduce() function
ifstatement? What if the last city in the list is unique?Setevery()certainly does not apply here. Check out the documentation.reduce()is closer, but you could probably just.map()the cities into a newSetand get itssize.