Skip to content

Instantly share code, notes, and snippets.

@petergi
Last active December 27, 2023 22:15
Show Gist options
  • Select an option

  • Save petergi/8b67d78f4cae297414d332580aa66c60 to your computer and use it in GitHub Desktop.

Select an option

Save petergi/8b67d78f4cae297414d332580aa66c60 to your computer and use it in GitHub Desktop.
Finds all unique values in an array
/**
* Returns an array containing the unique elements from the input array.
*
* @param {Array} arr - The input array.
* @return {Array} An array containing the unique elements from the input array.
*/
function uniqueElements(arr) {
const uniqueArr = []
const seen = new Set()
for (const element of arr) {
if (!seen.has(element)) {
uniqueArr.push(element)
seen.add(element)
}
}
return uniqueArr
}
uniqueElements([1, 2, 2, 3, 4, 4, 5]) // [1, 2, 3, 4, 5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment