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
Here's a script for getting a unique list of nonempty values in a column given the Sheet it's on and the header location of the column using an array to store the values and indexOf to find duplicates. You can then write the array wherever you'd like.
headerLocation is a Location object:
var Location = function(sheet, row, col) {
this.sheet = sheet;
this.row = row;
this.col = col;
this.addRow = function() { this.row = this.row + 1; }
this.addCol = function() { this.col = this.col + 1; }
this.getValue = function() { return sheet.getRange(this.row, this.col).getValue(); }
this.toString = function() { return "(" + this.row + "," + this.col + ")"; }
}
This is the function to read the column and return unique values:
/**
* Get unique values in column, assuming data starts after header
* @param {Sheet} sheet - Sheet with column to search
* @param {object} headerLocation - row and column numbers of the column header cell
* @returns {array} list of unique values in column
*/
function getUniqueColumnValues(sheet, headerLocation) {
let startRow = headerLocation.row + 1;
let lastRow = sheet.getLastRow();
let values = [];
for (i = startRow ; i <= lastRow ; i++) {
let value = sheet.getRange(i, headerLocation.col).getValue();
if ((value != "") && (values.indexOf(value) == -1)) {
values.push(value);
}
}
return values;
}
Or, using a Location to find the values:
function getUniqueColumnValues(sheet, headerLocation) {
let values = [];
let searchLocation = new Location(sheet, headerLocation.row + 1, headerLocation.col);
let lastRow = sheet.getLastRow();
while (searchLocation.row <= lastRow) {
let value = searchLocation.getValue();
if (values.indexOf(value) == -1) {
values.push(value);
}
searchLocation.addRow();
}
return values;
}