Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda