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

295
Visualizações
Search element in array of objects

Could someone guide me how to find an element in an array?

I always get false for elements that exist.

Thank you.

arr = new Array;
arr.push({x: "a", y: 1});
arr.push({x: "b", y: 2});
arr.push({x: "c", y: 3});
​
elem = {x: "c", y: 3};
​
if (arr.includes(elem)){
    console.log('true');
} else {
    console.log('false');
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You are looking for {x: "c", y: 3} object in arr and It will never be equal to any other object because {} !== {}.

Remember: Object are compared with reference but the primitives are checked by their value.

In your code you are checking an object reference with another reference, which is not equal so that's why it logs false.

If there are array of numbers then you should use includes as:

const arr = [10, 20, 30];

if(arr.includes(20)) console.log("true");
else console.log("false");

You can use find to find the element in the array

const arr = new Array();
arr.push({ x: "a", y: 1 });
arr.push({ x: "b", y: 2 });
arr.push({ x: "c", y: 3 });

const elem = { x: "c", y: 3 };

if (arr.find((o) => o.x === elem.x && o.y === elem.y)) {
  console.log("true");
} else {
  console.log("false");
}

about 4 years ago · Juan Pablo Isaza Relatório

0

since you are working with a 2d array i believe your object will be allways same for X and Y , so i suggest you to make a function like that for further use in your code

arr = new Array;
arr.push({x: "a", y: 1});
arr.push({x: "b", y: 2});
arr.push({x: "c", y: 3});

elem = {x: "c", y: 3};

console.log(findXY(arr,elem))

function findXY(arr,val){
  return arr.find(each=>{
    return each.x == val.x && each.y == val.y
  })
}

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