Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

use Array.every()

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

var isSameValue = ages.every((ele) => {
  return ele.age === 10;
});
console.log(isSameValue); //true
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!