skip to Main Content

In google Apps script i am pulling rows of numbers into an array

I need to find the sum of every element in that array

This code works fine: (This is pulling the values into the array)

   var test = [];
   test = sheet.getRange(13, 6, 4, 24).getValues();

I’ve tried a couple different formulas i’ve found and haven’t been able to get it to work right:

 function testSum (test) {
 let total = 0;
 for (const i of test) {
 total += i;
 }
 return total;
 }


 var test1 = test.flat();

 var test1 = test.reduce((a, b) => a + b, 0);

Tried everything i could find and nothing would work

3

Answers


  1.     const test = [
          [
            583.95,
            '',
            '',
            '',
            '',
            '',
            225,
            '',
            11,
            '',
            20,
            '',
            21.95,
            '',
            279,
            '',
            19,
            '',
            8,
            '',
            690,
            '',
            '',
            '',
          ],
          [
            145,
            '',
            80,
            '',
            10,
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            55,
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            110,
            '',
            '',
            '',
          ],
          ['', '', '', '', ''],
        ];
        
        const columnWiseSums = [];
        
        for (const ele  of test) {
            let sum = 0;
            columnWiseSums.push(ele.reduce((prev, curr) =>  typeof curr === 'number' ? prev + curr : prev, 0));
        }
    console.log(columnWiseSums);
    

    There are other ways to find sum as well, but I used array.reduce one

    Login or Signup to reply.
  2.  1. for 1D array
    
     const sumOfArrayElement = (input) => {
             return input.reduce((total, item)=>total+item)
            }
            sumOfArrayElement([3,2,4])
        
    
     2. For 2D Array
    
         const sum =[];
            test.forEach(item=>{
              sum.push(item.reduce((total,num)=> {
                return num!= ''?total +parseFloat(num):total;
                }));
            })
    
    Login or Signup to reply.
  3. this code will be make the mistake solucion.

    function testSum(test) {
      var sum = 0;
      for (var i = 0; i < test.length; i++) {
        for (var j = 0; j < test[i].length; j++) {
        
          if (typeof test[i][j] == "number") {
            sum += test[i][j]
          }
        }
      }
      return sum
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search