Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

check if items in array of unknown size all have the same property value

I have an array of undefined size that holds objects with the same propertynames. What I am looking for, is a clean way to check if all of these items have the same value assigned to a specific property or not.

Example
[{age:10}, {age:10}]

I need a way to return true in this case, since age is the same on all objects. If one object would have any other value than 10 it would have to return false.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My approach was a for loop, saving the first iterations value and check if the next is the same otherwise return. Is there a cleaner way of doing this?

>Solution :

You can do the following

const checkPropertyIsEqual = (myArray, propertyName) => {
    const res = myArray.map(arrayItem => arrayItem[propertyName]);
    return (new Set(res).size === 1); 
}


console.log(checkPropertyIsEqual([{age: 10}, {age: 10}], "age"))
console.log(checkPropertyIsEqual([{age: 20}, {age: 10}], "age"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading