I would like to check multiple arrays if their sum is equal to zero and if yes, output yes. But only the first array is being read by the code.
There should be 3 outputs of (true or false) but I'm getting only 1 output instead
const arr0 = [3];
const arr1 = [4];
const arr2 = [2, 8, -9, 1];
const arr = [arr0, arr1, arr2];
const zeroSum = arr => {
const map = new Map();
let sum = 0;
for(let i = 0; i < arr.length; i++){
sum += arr[i];
if(sum === 0 || map.get(sum)){
return true;
};
map.set(sum, i);
};
return false;
};
console.log(zeroSum(arr));
As I mentioned in my comment arr[i] will always be an array. Trying to add that to sum will result in a string. You'll never get the result you want. To sum the elements of each array you need an inner loop to go over each element and add those to sum instead.
Currently you're only returning one thing: true or false. It sounds like you want an array into which you add the results of each sum, and then you can return that.
Not sure what you're using Map for so I've removed it from my example.
const arr0 = [3];
const arr1 = [4];
const arr2 = [0];
const arr3 = [2, 8, -9, 1];
const arr = [arr0, arr1, arr2, arr3];
function zeroSum(arr) {
// Create an output array
const out = [];
// Loop over the arrays
for (let i = 0; i < arr.length; i++) {
// Reset the sum for each iteration
let sum = 0;
const inner = arr[i];
// Loop over the elements of each array
for (let j = 0; j < inner.length; j++) {
// Add the elements to `sum`
sum += inner[j];
}
// Push either true or false to
// the output array depending on the
// result of the condition
if (sum === 0) {
out.push(true);
} else {
out.push(false);
}
}
// Finally return the array
return out;
}
console.log(zeroSum(arr));