Divide cell by the number of people

This is not intended to be a cell function but as a standard function it provides the desired output.

function myfunk() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  const osh = ss.getSheetByName('Sheet1');
  const vs = sh.getRange(2,1,2,4).getValues();
  let a = [];
  vs.forEach((r,i) => {
    let c2 = r[2].toString().split(",");
    c2.forEach(e => {
      a.push([r[0],r[1],e,r[3]/c2.length]);
    });
  });
  osh.clearContents();
  osh.getRange(2,1,a.length,a[0].length).setValues(a);
}

input:

data1 data2 a,b,c,d,e 1000
data3 data4 f,g,h,i 2000

output:

A B C D
data1 data2 a 200
data1 data2 b 200
data1 data2 c 200
data1 data2 d 200
data1 data2 e 200
data3 data4 f 500
data3 data4 g 500
data3 data4 h 500
data3 data4 i 500

Try it this way for more rows and columns

function myfunk() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  const osh = ss.getSheetByName('Sheet1');
  const vs = sh.getRange(2,1,sh.getLastRow() - 1,sh.getLastColumn()).getValues();//gets the entire column
  let a = [];
  vs.forEach((r,i) => {
    let c2 = r[2].toString().split(",");
    c2.forEach(e => {
      let row = r.slice();//keeps each element of the output array independent
      row.splice(2,2,e,row[3]/c2.length);//replace elements 2 and 3
      a.push(row);
    });
  });
  osh.clearContents();
  osh.getRange(2,1,a.length,a[0].length).setValues(a);
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top