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

180
Visualizações
Is pushing an object to an array async operation?

I was doing one problem-solving program where I had to find all the pairs from an array that adds up to a target (classic two-sum program just with a little addition). This was my first approach:

let findPair = (arr, target) => {
    let res = [];
    let mappingArr = new Map()
    let obj = {
        first: 0,
        second: 0
    }

    for(let i=0; i<arr.length; i++){
        let comp = target - arr[i];
        if(mappingArr.has(comp)){
            obj.first = arr[mappingArr.get(comp)];
            obj.second = arr[i];
            res.push(obj)
        } else {
            mappingArr.set(arr[i], i)
        }
    }
    return res;
}

let arr = [8, 7, 2, 5, 3, 1]
let target = 10;

let sumPair = findPair(arr, target);
console.log(sumPair);

** This should output: [{first: 8, second: 2},{first: 7, second: 3}] but instead it prints: [{first: 7, second: 3},{first: 7, second: 3}] **

Now if I make one little change in the for loop like this:

if(mappingArr.has(comp)){
    res.push({first: arr[mappingArr.get(comp)], second: arr[i]});
} else {
    mappingArr.set(arr[i], i)
}

by directly pushing the object instead of first assigning to one object and then pushing the object to an array, it works fine.

I also faced a similar issue with my back-end code once. That time too I couldn't understand why the issue was arising.

Any idea why this is happening.?

Thanks.!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

In your first version, you just have one obj:

let obj = {
    first: 0,
    second: 0
}

The loop then mutates that same object, and pushes it unto the array. This means the array gets multiple references to the same object. Even when the object is already pushed to the array, the next iteration mutates that object.

Since there is only one such object, it is expected that you see the same output for all entries in the array.

The easiest solution is to define a new object in every iteration. So move the above let inside the loop, and it will work. But what you did in the second version uses the same principle: you create a new object each time you push it unto the array.

about 4 years ago · Juan Pablo Isaza Relatório

0

The issue is happening because you have declared variable "obj" outside for loop, so it's reference is always same when you modify it in iterations.

Declare it inside loop and that will solve your problem.

for(let i=0; i<arr.length; i++){
   let obj = {
        first: 0,
        second: 0
    }
        let comp = target - arr[i];
        if(mappingArr.has(comp)){
            obj.first = arr[mappingArr.get(comp)];
            obj.second = arr[i];
            res.push(obj)
        } else {
            mappingArr.set(arr[i], i)
        }
    }
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