Home > Software engineering >  check if items in array of unknown size all have the same property value
check if items in array of unknown size all have the same property value

Time:05-13

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?

CodePudding user response:

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

CodePudding user response:

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
};
[a, b, c, d].filter(x => x.hasOwnProperty('age')).map(x => x.age).every((x, _, arr) => x === arr[0]);

This should give you the desired result.

CodePudding user response:

use Array.every()

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

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

CodePudding user response:

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'));

  • Related