0

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));
4
  • Do you want the sum of the arrays merged together, or just the sum of each independent array? Commented Nov 19, 2021 at 5:46
  • sum of each independent array only @Andy Commented Nov 19, 2021 at 5:47
  • The key line is sum += arr[i]. arr[i] is an array and you're trying to add it to 0. You need to loop over the elements of arr[i] and add those to sum which would need to be declared for each outer loop. Commented Nov 19, 2021 at 5:56
  • 1
    @Andy Thank you, I'm still learning array. As of now I still didn't get it. But I'll take note of your comment Commented Nov 19, 2021 at 6:13

1 Answer 1

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

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

  3. 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));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.