简体   繁体   中英

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

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

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

Because it is a 2 dimensional array so first you need to flatten the array to make it one dimensional and then use reduce to sum the array

do this way in es6 approach

arr.flat().reduce( (p,n)=> p+n, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM