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