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.
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"))