Tuesday 15 August 2023

Sort through an array of duplicates with Sets

The following JavaScript code is a quick and easy alternative to sorting through an array of duplicates. It was highlighted to me by my colleague Tom Smith. As before it is designed to go through an array of values that contains duplicates and create a new array of only the unique ones, but not arranged alphabetically in this instance.

Sort an array with JavaScript Sets
Sort an array with JavaScript Sets

The Code

The main aspect of this code is 'JavaScript Sets' that does all of the work for us. In this example it is being run inside of an array so the values are directly populated into it.

var uniqueArray = [
    ...new Set(messyArray)
];


Download

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

No comments:

Post a Comment