Gathering all the unique values from one column and outputting them in another column..?

前端 未结 4 1666
眼角桃花
眼角桃花 2021-01-05 18:35

I have this form of a spreadsheet:

 A   B   C  D
abc abc abc 1
def ghi jkl 1
mno pqr stu 3
vwx yza bcd 4
mno pqr stu 5
mno pqr stu 5
vwx yza bcd 5
mno pqr st         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-05 19:03

    Currently, in V8 engine, the easiest way to do this is to use Set:

    /**
     * @returns {Object[]} Gets unique values in a 2D array
     * @param {Object[][]} array2d
     * @private
     */
    const getUnique_ = array2d => [...new Set(array2d.flat())];
    
    /**
     * Gets Values from a column, makes it unique and sets the modified values
     *   to the next column
     * @param {string} sheetName
     * @param {number} column Number of the column to uniquify
     * @param {number} headers Number of headers
     * @returns void
     */
    const uniquifyAColumn = (sheetName = 'Sheet1', column = 3, headers = 1) => {
      const sh = SpreadsheetApp.getActive().getSheetByName(sheetName),
        rg = sh.getRange(1 + headers, column, sh.getLastRow() - headers, 1),
        values = rg.getValues(),
        uniqueValues = getUnique_(values).map(e => [e]);
      rg.offset(0, 1, uniqueValues.length).setValues(uniqueValues);
    };
    

提交回复
热议问题