'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.

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 1:[1]

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

Solution 2:[2]

use Array.every()

const ages = [{ age: 10 }, { age: 10 }, { age: 10 }];

var isSameValue = ages.every((ele) => {
  return ele.age === 10;
});
console.log(isSameValue); //true

Solution 3:[3]

Write a little helper function that accepts the array, and the property to inspect, create an array of values using map and check if they are all same with every.

const arr = [{age:10}, {age:10}];
const arr2 = [{age:1}, {age:10}];
const arr3 = [{name:'Bob'}, {name:'Bob'}];
const arr4 = [{name:'Bob'}, {name:'Steve'}];

// For every object in the array are all the values
// of the property the same value
function sameValue(arr, prop) {
  if (!arr.length) return 'Array is empty';
  return arr
    .map(el => el[prop])
    .every((el, _, arr) => el === arr[0]);
}

console.log(sameValue(arr, 'age'));
console.log(sameValue(arr2, 'age'));
console.log(sameValue(arr3, 'name'));
console.log(sameValue(arr4, 'name'));
console.log(sameValue([], 'name'));

Solution 4:[4]

Not sure if it's that much cleaner, but you could try using array methods:

const a = {
  someOtherProp: true
};
const b = {
  age: 10
};
const c = {
  age: 10
};
const d = {
  age: 20
};

let shouldBeTrue = [a, b, c].filter(x => x.hasOwnProperty('age')).map(x => x.age).every((x, _, arr) => x === arr[0]);
let shouldBeFalse = [a, b, c, d].filter(x => x.hasOwnProperty('age')).map(x => x.age).every((x, _, arr) => x === arr[0]);

console.log(shouldBeTrue);
console.log(shouldBeFalse);

This should give you the desired result.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Aayush Bhattacharya
Solution 3
Solution 4