Get All Unique Values from Array in JavaScript

In JavaScript, an array is a special type of object that holds a collection of items. Each item in an array is called an element, and each element can have any type of value, including primitive data types (numbers, strings, booleans) and other objects. Arrays are ordered collections, meaning that the elements have a specific order and can be accessed using their index.

In this tutorial, we will learn how to get all unique values from 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 ["😁", "💀", "💩", "💙"]

2. 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 ["😁", "💀", "💩", "💙"]

3. Using the Set method.

const someArray = ['😁', '💀', '💀', '💩', '💙', '😁', '💙'];

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

console.log(getUniqueValues(someArray))
// Result ["😁", "💀", "💩", "💙"]

#js #javascript

2.05 GEEK