Home > database >  Duplicate values on column A to column B - Google Apps Script
Duplicate values on column A to column B - Google Apps Script

Time:09-24

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

CodePudding user response:

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)}});
  sheet.getRange(1,2,output.length,1).setValues(output.map(e=>[e]));
}
  • Related