Search code examples
javascriptarraysobjectexistsany

How can I use .some() to find if an array of objects contains a specific property value


I've an array containing objects, where every object represents a person that's going to a video theatre. The objects contains properties such as Name, Age and Hobby. If there is (atleast) one person younger than 18, the variable censor should be set to true.

My code below yields the value false, despite Tim being younger than 18. Is it not possible to use .some() this way, or what am I doing wrong?

var persons = [
    {Name: "Joel", Age:25, Hobby:"Fishing"},
    {Name: "Michael", Age:31, Hobby:"Astronomy"},
    {Name: "Tim", Age:12, Hobby:"Video Games"},
]

var censor = persons.some((person) => {person.Age < 18})
console.log(censor) --> false

Solution

  • You are missing a return in your callback that is why it is always false,

    either use:

    var censor = persons.some(person => person.Age < 18)
    

    or

    var censor = persons.some(person => {return person.Age < 18 })