Get all unique values in a JavaScript array (remove duplicates)

Let's understand how to get all the unique values in a JavaScript array, i.e., how to remove duplicate values in array?
Submitted by Pratishtha Saxena, on June 18, 2022

To make sure whether the given array contains all unique values (no repeated values) then there are the following ways to do so in JavaScript:

  1. Sets
  2. Filter
  3. ForEach

1) Using Sets

Sets in JavaScript are used to store only unique values. Set is a collection of unique values.


new Set()

Now, to remove the duplicate values in an array, we can create a set of that array. We'll use spread operator for this so that the output is also in the form of array data type.

Example 1:

    const colors = ["Black","White","Yellow","Blue","Pink","Black","Red","Yellow","Violet","Green","Green"];

    const unique = [ Set(colors)];


Example 1: Get all unique values

2) Using filter() Method

This method in JavaScript creates a new array with the values that passes the condition specified within. The array is passed through the filter method and the values that fulfils the condition is put in the new array.


array.filter(function(currentValue, index, arr), thisValue)

Example 2:

    const colors = ["Black","White","Yellow","Blue","Pink","Black","Red","Yellow","Violet","Green","Green"];

    const unique = colors.filter((value,index)=>{
        return colors.indexOf(value) === index;


Example 2: Get all unique values

3) Using forEach() Method

Unlike sets and filter() methods, this method does not directly removes all the duplicate values from an array. Here, we need to write down some logic to remove repeated values. This logic is then put in a loop that runs for each value in the given array.



Example 3:

    const colors = ["Black","White","Yellow","Blue","Pink","Black","Red","Yellow","Violet","Green","Green"];

    // using foreach
    function uniqueElements(array){
        const unique = [];
        return unique;



Example 3: Get all unique values

JavaScript Examples »

Related Examples

All JavaScript Examples

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.