This is the simple code which remove all the duplicate values and working fine.
function removeDuplicate2ndPhase() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Hourly Data');
var lastRow = sheet.getLastRow();
var range = sheet.getRange('B3:M' + lastRow);
range.removeDuplicates([3]);
}
all i want to remove duplicate data with it’s original values too.
I filter data on the basis of column C and i tried this code it get the desired results but problem if i manually change a value in column C and all other row data is same still it delete that row. Which I don’t want.
function keepUniqueValues() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Hourly Data');
var lastRow = sheet.getLastRow();
var range = sheet.getRange('B3:M' + lastRow);
// Get all values in the specified range
var values = range.getValues();
var uniqueCheck = {};
var uniqueValues = [];
// Loop through each row in the range
for (var i = 0; i < values.length; i++) {
var row = values[i];
var key = row[2]; // Assuming the third column (index 2) is the column to check for duplicates
// Check if the key is already in uniqueCheck
if (!uniqueCheck[key]) {
uniqueCheck[key] = true;
uniqueValues.push(row);
} else {
// If the key is already in uniqueCheck, remove it from uniqueValues (if it exists)
var indexToRemove = uniqueValues.findIndex(function(existingRow) {
return existingRow[2] === key; // Check if the existing row has the same key value
});
if (indexToRemove !== -1) {
uniqueValues.splice(indexToRemove, 1);
}
}
}
// Clear existing data in the range
range.clearContent();
// Set the unique values back to the range
if (uniqueValues.length > 0) {
range.offset(0, 0, uniqueValues.length, uniqueValues[0].length).setValues(uniqueValues);
}
}
2
Answers
Use
Array.map()
andArray.filter()
, like this:See Array.map() and Array.filter().