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

114
Visualizações
Using for loop to add elements to an empty array

I am trying to remove any duplicate from a JSON-like data list, so if there are two or more items with the same name, I just want to keep one. I am trying to solve it with this naive approach. And when I try to push the (data[i].name, data[i].age) to an empty array newData, the end result is just an empty array. But, if the array already had some value, it works. Here's the console:

[]  //this result is with empty array
(9) [1, "player1", 10, "player2", 30]  //this result is with newData.push(1);

Here the code

function someFunction(data) {
    const newData = [];
    newData.push(1);
    
      for (var i = 0; i < data.length; i++) {
        for (var j = 0; j < newData.length; j++) {
          if (i !== j) {
            if (!newData.includes(data[i].name)) {
              newData.push(data[i].name, data[i].age);
            }
          }
        }
      }
    
      return newData;
}

lets say I have a data list like this:

const data = [
 {
  name: "player1",
  score: 10
 },
 {
  name: "player2",
  score: 30
 }, 
{
  name: "player1",
  score: 10
 },
]

Can someone help to explain? And I came up with this idea on my own, I know I can use something like array.reduce() or a hashmap, but I really want to know if I can do it this way. Also, is there any way that I can push (data[i].name, data[i].age) to the array as one element? I think I am adding two at one iteration. Thank you!

about 4 years ago · Juan Pablo Isaza
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