Tuesday 20 December 2022

Sort through an array of duplicates

The following Google Apps Script is designed to go through an array of values that contains duplicates and create a new array of only the unique ones, arranged alphabetically. I needed this code when looping through files in a Google Drive folder where tutors and their groups formed part of the filename that I needed to extract for the end file that was created.

Remove array duplicates
Remove array duplicates

The Code

There are a few elements of the code worth pointing out, starting with a quick JavaScript 'sort' of the initial array of duplicates so that they are alphabetised. This is more because I wanted them to be nicely organised at the end:

var rawArray = ['Dave', 'Jim', 'Dave', 'Nicky', 'Nicky', 'Bob', 'Bob', 'Bob'];
rawArray.sort();

We use 'forEach' to iterate through every item in our initial array and then the JavaScript method 'includes' to see if the item currently exists - providing a true/false response:

var exists = cleanArray.includes(name);

Depending upon if it already exists or not we can then choose to push it into our new array of unique values only:

if (!exists) {
      // does not exist, push into empty array
      cleanArray.push(name);
}
else {
      // does already exist, do nothing
}

 

 

Download

Sort through an array of duplicates download (please use 'Overview' > 'Make a copy' for your own version).


No comments:

Post a Comment