Skip to content
Advertisement

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.!

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement