RemcoE33

Sum each row / Sum each header

Sep 21st, 2022
811
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2. * Returns the sum of each row in a multiple column dataset.
  3. *
  4. * @param {A2:D10} data The input data
  5. * @return {array} sums.
  6. * @customfunction
  7. */
  8. function SUM_EACH_ROW(data) {
  9.   const results = []
  10.  
  11.   data.forEach(row => {
  12.     let n = 0
  13.     row.forEach(col => {
  14.       if (typeof col == 'number') {
  15.         n += col
  16.       }
  17.     })
  18.     if (n == 0) {
  19.       results.push([""])
  20.     } else {
  21.       results.push([n])
  22.     }
  23.   })
  24.  
  25.   return results
  26. }
  27.  
  28. /**
  29. * Returns the sum of each column with column headers.
  30. *
  31. * @param {A1:D10} data The input data (including the headers)
  32. * @return {array} sums.
  33. * @customfunction
  34. */
  35. function SUM_EACH_COL(data){
  36.   const resultsObj = {}
  37.  
  38.   data[0].forEach((header, i) => {
  39.     resultsObj[i] = {header, sum: 0}
  40.   })
  41.  
  42.   data.unshift()
  43.  
  44.   data.forEach((row) => {
  45.     row.forEach((col, i) => {
  46.       if (typeof col == 'number') {
  47.         resultsObj[i].sum += col
  48.       }
  49.     })
  50.   })
  51.  
  52.   return Object.values(resultsObj).map(res => {
  53.     const { header, sum } = res
  54.     return [header, sum]
  55.   })
  56.  
  57. }
  58.  
  59.  
  60.  
Tags: COL sum row
Advertisement
Add Comment
Please, Sign In to add comment