SpreadsheetApp how to return unique values from an array
in this post how to count a duplicate values and show theme in sheetname('test2') Range ('B2:B7') here my google sheet https://docs.google.com/spreadsheets/d/1HN0XCLrEzlRkInIv6xFnhCFnhZabu7Y-Tz1dvYvsGQM/edit?usp=sharing
CodePudding user response:
In your situation, how about the following sample script?
Sample script:
function myFunction() {
const srcSheetName = "test"; // Please set the source sheet name.
const dstSheetName = "test2"; // Please set the destination sheet name.
// Retrieve source and destination sheets.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const [srcSheet, dstSheet] = [srcSheetName, dstSheetName].map(s => ss.getSheetByName(s));
// Retrieve source values and create an object for putting to the destination sheet.
const srcValues = srcSheet.getRange("A2:A" srcSheet.getLastRow()).getValues();
const obj = srcValues.reduce((o, [a]) => (o[a] = o[a] ? o[a] 1 : 1, o), {});
// Retrieve the values of column "A" from the destination sheet and create an array for putting to Spreadsheet.
const dstRange = dstSheet.getRange("A2:A" dstSheet.getLastRow());
const dstValues = dstRange.getDisplayValues().map(([a]) => [obj[a] || 0]);
// Put the result values to the column "B" of the destination sheet.
dstRange.offset(0, 1).setValues(dstValues);
}
- From your provided Spreadsheet, the sample sheet names are
test
andtest2
. Please modify this for your actual situation. - When you run this script, the values are retrieved from the source sheet and the count of each value is calculated. And, the result values are put to the column "B" of the destination sheet.
Note:
- This sample script is for your provided Spreadsheet. When you change the structure of the Spreadsheet, this script might not be able to be used. Please be careful about this.