Duplicate values on column A to column B – Google Apps Script


I’m trying to achieve the following result:

enter image description here

So if column A has duplicate values, I want to show these duplicate values on column B. Here is what I have tried so far. But the code just makes Apple to show two times in a column B. How would I need to alter my code to make it work the way I want?

function findDuplicates() {
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sheet = ss.getActiveSheet()
  var lastRow = sheet.getLastRow()
  var data = sheet.getRange(1,1,lastRow).getValues()

  var dataUnique = data.reduce(function (out, item) {
  return out.concat(out.filter(function (comp) {
    return item.toString() != comp.toString();
  }).length ? [] : [item])
  }, []);

  var newValues = sheet.getRange(1,2,dataUnique.length).setValues(dataUnique)

This is the result when I run the code:

enter image description here


This is a spreadsheet created specifically to address this question. It contains the following code that will take values from A and output the result in column B:

function myFunction() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var input = sheet.getRange('A1:A').getValues().filter(e=>e[0]).map(e=>e[0]);
  var inputLower = input.map(e=>e.toLowerCase());

  var output = new Array();
  input.forEach(function (e,i,arr){if(inputLower.indexOf(e.toLowerCase())!=i && output.indexOf(e)==-1){output.push(e)}});

Answered By – MattKing

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published