user11580667
user11580667

Reputation:

How to return a number of objects in Javascript?

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;
});

}

Upvotes: 0

Views: 187

Answers (1)

DustInComp
DustInComp

Reputation: 2666

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

Upvotes: 2

Related Questions