Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

122
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda