0

I have a function which receives an array of person objects. The function should return the number of persons who lives in the city of Syndey. But, I am getting problem in returning a number of the person who lives in Sydney. What should I do? Anyone can help me, please?

This is the code that I have created:

function numberOfPeopleInSydney(person) {

   people.forEach(function (arrayItem) {
    if(arrayItem.lives.city==="Sydney")

        return arrayItem.name;
});

}
3
  • It might not matter too much but you've spelled Sydney wrong pretty much everywhere. Commented May 31, 2019 at 10:51
  • 1
    forEach is a wrong choice, this return does nothing. And tallyPeopleInSyndey misses return statement Commented May 31, 2019 at 10:54
  • 1
    You even get person but call forEach on people... Commented May 31, 2019 at 10:57

1 Answer 1

2

forEach just calls the function you pass it with every element of the array but doesn't use the returned values.

If you want to keep count of the people who pass your condition, you'll have to increment some kind of counter in the if-block, also fix the argument name and add a return in the actual function, like barbsan mentioned:

function tallyPeopleInSyndey(people) {
    var count = 0
    people.forEach(function (arrayItem) {
        if(arrayItem.lives.city==="Syndey")
            count++
    })
    return count
}

Personally, I'd just filter people by the condition and get the length of the resulting array:

people.filter(function(person) {
    return person.lives.city === "Syndey"
}).length
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.