Nahid Nasem
Nahid Nasem

Reputation: 27

How can I add the numbers in the following code?

I have an array named arr = [[1,2],4] , and for loops to access the numbers. But I can't seem to add the last number. Why is it not working?

    let arr = [[1,2],4];       
    let total = 0;
        
    for(let i = 0; i < arr.length; i++) {
       for(let j = 0; j < arr[i].length; j++) {
          total += arr[i][j];
       }
    }
    console.log(arr.length)  // returns length = 2
    console.log(total);      // returns total = 3

Upvotes: 2

Views: 75

Answers (2)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Since the values can be array or numbers, Just add the check before doing the inner loop

   if (!Array.isArray(arr[i])) {
      total += arr[i];
      continue;
   }

    let arr = [[1,2],4];       
    let total = 0;
        
    for(let i = 0; i < arr.length; i++) {
       if (!Array.isArray(arr[i])) {
          total += arr[i];
          continue;
       }
       for(let j = 0; j < arr[i].length; j++) {
          total += arr[i][j];
       }
    }
    console.log(arr.length)  // returns length = 2
    console.log(total);

Upvotes: 0

Nick Parsons
Nick Parsons

Reputation: 50684

Your issue is that your array doesn't just consist of only arrays, it consists of both single numbers and nested arrays. As a result, your inner loop won't be able to loop over the number 4 as it is not an array (and so it won't have a .length property).

let arr = [[1,2],4];
// no issues-^   ^-- no `.length` property  (inner for loop won't run)

For a problem like this, you can make use of a recursive function, which when you encounter a nested array, you can recall your function to perform the addition for that array.

See example below (and code comments):

function sumNums(arr) {
  let total = 0;
  for (let i = 0; i < arr.length; i++) {
    if(Array.isArray(arr[i])) { // If current element (arr[i]) is an array, then call the sumNums function to sum it 
      total += sumNums(arr[i]);
    } else {
      total += arr[i]; // If it is not an array, then add the current number to the total
    }
  }
  return total;
}

let arr = [[1,2],4];
console.log(sumNums(arr)); // 7

You can also make use of a recursive call with .reduce() if you would like to take that approach:

const arr = [[1,2],4];
const result = arr.reduce(function sum(acc, v) {
  return acc + (Array.isArray(v) ? v.reduce(sum, 0) : v); 
}, 0);
console.log(result); // 7

Upvotes: 2

Related Questions