3

I have an array of object like this :

const object = [
     {name: 'John', age: 15},
     {name: 'Victor', age: 15},
     {name: 'Emile', age: 14}
     ]

I need to check if in this array all age are 15. ( just need a boolean for answer ) I need to use something like 'every' method but how with an object ?

3
  • 2
    every() works with an array. The callback function can check the property of the object. Commented Apr 28, 2020 at 17:59
  • obj.age == 15 Commented Apr 28, 2020 at 17:59
  • I asume you mean are 15 or older? Commented Apr 28, 2020 at 18:04

3 Answers 3

5

You need to use every:

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. Array.prototype.every

So the code will be like:

const object = [
    {name: 'John', age: 15},
    {name: 'Victor', age: 15},
    {name: 'Emile', age: 14}
]
     
const isValid = object.every(item => item.age === 15)
console.log({isValid})

This is js functional ability to test all your elements states.

Sign up to request clarification or add additional context in comments.

Comments

2

You just need to extract the property you want to compare

const object = [ {name: 'John', age: 15},{name: 'Victor', age: 15},{name: 'Emile', age: 14}]

let op = object.every(({ age }) => age === 15)

console.log(op)

Comments

0

You can compare the length of the array with length of array of objects with required age.

const object = [ 
    {name: 'John', age: 15},
    {name: 'Victor', age: 15},
    {name: 'Emile', age: 14}
];
function hasAge(pAge, object) {
    return object.length === object.filter(({ age }) => age === pAge).length;
}
console.log(hasAge(15, object));

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.