Skip to content

Instantly share code, notes, and snippets.

@DoctorDerek
Last active November 4, 2020 19:29
Show Gist options
  • Select an option

  • Save DoctorDerek/d351e71aa45cc94c665bf0a37ccf89e1 to your computer and use it in GitHub Desktop.

Select an option

Save DoctorDerek/d351e71aa45cc94c665bf0a37ccf89e1 to your computer and use it in GitHub Desktop.
Using Set for unique primitive values in an array in JavaScript
// Set up a number array with duplicate values
const myNumberArray = [37, 37, 370, 3700, 3700, 37]
// Using Set with different approaches
// 1) Set using for...of loop
const myNumberSetForOf = new Set()
for (const myNumber of myNumberArray) {
myNumberSetForOf.add(myNumber)
}
// 2) Set using .forEach()
const myNumberSetForEach = new Set()
myNumberArray.forEach((aNumber) => {
myNumberSetForEach.add(aNumber)
})
// 3) Set using the Set() constructor with an iterable object
// Note that arrays are iterable objects, but JavaScript objects are not
const myNumberSetConstructor = new Set(myNumberArray)
// Convert any Set() back into an array using Array.from()
console.log(Array.from(myNumberSetConstructor)) // [37,370,3700]
// One-liner:
console.log(Array.from(new Set([37, 37, 370, 3700, 3700, 37]))) // [37,370,3700]
// Set's behavior is the same for all primitive values
// including strings, booleans, NaN, undefined, and null
const myStringArray = ["πŸ™Œ", "πŸ—½", "😜", "πŸ”₯", "πŸ’―", "πŸ’―", "πŸ”₯", "πŸ—½", "😜"]
console.log(Array.from(new Set(myStringArray))) // ["πŸ™Œ","πŸ—½","😜","πŸ”₯","πŸ’―"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment