Skip to content

Instantly share code, notes, and snippets.

@mojaray2k
Created May 28, 2020 15:48
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mojaray2k/36eea185fc2b4c9cced12bb30b3d74b0 to your computer and use it in GitHub Desktop.
Save mojaray2k/36eea185fc2b4c9cced12bb30b3d74b0 to your computer and use it in GitHub Desktop.
3 Ways to get unique values from an array in Javascript

Here are 3 ways to retrieve unique values from arrays in Javascript

  1. The array.filter method which is a higher order function which means it takes a function as it's argument.
const someArray = ['😁', 'πŸ’€', 'πŸ’€', 'πŸ’©', 'πŸ’™', '😁', 'πŸ’™'];

const getUniqueValues = (array) => (
  array.filter((currentValue, index, arr) => (
		arr.indexOf(currentValue) === index
	))
)

console.log(getUniqueValues(someArray))
// Result ["😁", "πŸ’€", "πŸ’©", "πŸ’™"]
  1. The array.reduce method which is a higher order function which means it takes a function as it's argument.
const someArray = ['😁', 'πŸ’€', 'πŸ’€', 'πŸ’©', 'πŸ’™', '😁', 'πŸ’™'];

const getUniqueValues = (array) => (
  array.reduce((accumulator, currentValue) => (
    accumulator.includes(currentValue) ? accumulator : [...accumulator, currentValue]
  ), [])	
)

console.log(getUniqueValues(someArray))
// Result ["😁", "πŸ’€", "πŸ’©", "πŸ’™"]
  1. Using the Set method.
const someArray = ['😁', 'πŸ’€', 'πŸ’€', 'πŸ’©', 'πŸ’™', '😁', 'πŸ’™'];

const getUniqueValues = (array) => (
	[...new Set(array)]
)

console.log(getUniqueValues(someArray))
// Result ["😁", "πŸ’€", "πŸ’©", "πŸ’™"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment