How to get all unique values in an array in javascript – Definitive Guide?

Arrays are used to store a collection of multiple items under a single variable name.

You can get all unique values in an array in Javascript using the Set […new Set(values)] method.

In this tutorial, you’ll learn about the different methods to get all unique values in an array.

If You’re in Hurry…

You can use the code snippet to get all unique values in an array in javascript.

Code

    var birds= ["owl", "owl", "dove", "parrot", "owl", "dove"];

    let uniqueBirds = [...new Set(birds)];

    console.log(uniqueBirds );

Output

    ["owl","dove","parrot"]

If You Want to Understand Details, Read on…

Using Set()

Set allows you to store values of any data type accepting only unique values(primitive or object references).
A value in a Set can occur only once, making it unique in the Set’s collection.
Set can be used to get all unique values in an array easily and faster than other ways.
Code

    var values = ["owl", 1, "owl", "dove", 1, "2", true, true, false];

    let uniqueValues = [...new Set(values)];

    console.log(uniqueValues); 

Output

    ["owl", 1, "dove", "2", true, false]

As Set accepts only unique values and when you pass an array to the Set constructor([...new Set(values)]), it retains and returns the unique values by removing the duplicate values.

You can also use Set to get unique values in the Javascript object arrays,
Code

    let birdsObj = [{
      id: '100',
      name: 'owl'
    }, {
        id: '102',
      name: 'dove'
    }, {
        id: '100',
      name: 'dove'
    }, {
        id: '102',
      name: 'owl'
    }];

    const uniqueBirdsObj = [... new Set(birdsObj.map(data => data.name))];

    console.log(uniqueBirdsObj);

Output

    ["owl", "dove"]

The above example extracts the unique elements of the field(.name) in the Javascript object array.
Set constructor is provided with all the values of the field(name) in the object(birdsObj) and it returns the unique values present in the array object.

Using Helper array[]

You can use a simple For Loop iteration and a helper array to get all unique values in an array.
Code

    var values = ["owl", 1, "owl", "dove", 1, "2", true, true, false];

    var uniqueValues = [];

    for (var i=0, len=values.length; i<len; i++)

        if (uniqueValues.indexOf(values[i]) === -1 && values[i] !== '')

            uniqueValues.push(values[i]);

      console.log(uniqueValues);

Output

    ["owl", 1, "dove", "2", true, false]

Here, For loop is used to iterate through the array and check its current value’s presence in the helper array(unique values) using indexOf method.
– If the current value is already present in the helper array, you need to ignore the value and continue the iteration.
– If the current value is not present in the helper array, then add the new value to the helper array.

Once the iteration is completed, the helper array will hold the unique values.

Using filter() + indexOf()

The Filter method is used to create a new array by applying the condition on the array.
Let us see one example to get all unique values in an array using ES5, which most browsers support.
Code

    var birds = ["owl", "dove", "owl", "dove", "parrot"];

    var uniqueBirds = birds.filter(uniqueCheck);

    console.log(uniqueBirds); 


function uniqueCheck(value, index, self) {

  return self.indexOf(value) === index;

}

Output

    ["owl", "dove", "parrot"]

The filter() method will iterate through each value in the array and get the index position of the current value using indexOf() and checks against the current index.

– If both value matches then it is considered as the first occurrence and that value is returned.

– If both values are different then it is already present in the array, so it will ignore that value in the return array.

Now let us see one more example using ES6 way of implementation,
Code

    var birds = ["owl", "dove", "owl", "dove", "parrot"];

    var uniqueBirds = birds.filter((v, i, a) => a.indexOf(v) === i);

    console.log(uniqueBirds); //["owl", "dove", "parrot"]

Output

    ["owl", "dove", "parrot"]

Using filter() + includes()

This is similar to the above(filter + IndexOf) approach but the only difference is, that here you use includes() method inside the filter() condition.

The filter() method will iterate through each value in the array and the current value is given to .includes() method to check for its presence by having the next index position of the current value as the start index.

– If the includes() returns false, it confirms that no more value matching the current value is present in the array and now the current value is returned.

– If the includes() returns true, then it states there is another value matching the current value in the array, so the current value will not be returned.

Code

    var values = ["owl", 1, "owl", "dove", 1, "2", true, true, false];

    var uniqueValues = values.filter((v,i) => !values.includes(v,i+1));

    console.log(uniqueValues);

Output

    ["owl", "dove", 1, "2", true, false]

Using filter() + sort()

Here, you have to sort() the array first and arrange the values in order.
Now using.filter() method, iterate the sorted array and check the current array value against the next array value.
– If both values are different, the current value will be returned and continue the iteration.
– If both values are identical, iteration will continue by ignoring the current value.
Code

    var values = ["owl", 1, "owl", "dove", 1, "2", true, true, false];

    var valuesSorted = values.sort();

    const uniqueValues = valuesSorted.filter((e, i) => valuesSorted[i] != valuesSorted[i+1]);

   console.log(uniqueValues);

Output

    [1, "2", "dove", false, "owl", true]

Using reduce()+ indexOf()

Reduce() method accepts a user-supplied “reducer” callback function on the element of the array, in order, to pass in the return value from the calculation on the previous element.

Code

    var values = ["owl", 1, "owl", "dove", 1, "2", true, true, false];

    var uniqueValues = values.reduce(function(prev, cur) {

      return (prev.indexOf(cur) < 0) ? prev.concat([cur]) : prev;

     }, [])

    console.log(uniqueValues);

Output

    ["owl", 1, "dove", "2", true, false]

In the above example, after iterating the array using the .reduce() method, the current-value (cur) is checked(using indexOf) against the previous-value(prev) array.
– If the previous-value array does not contain the current-value, then the current-value will be added to the previous-value array.

– If present, then the previous-value remains unchanged.

Using reduce() + filter() for objects

You can use .reduce() along with .filter() method to get all unique javascript objects in an array.
Here, you will see an example to return complete unique Javascript objects, not just the field.
Code

    let birdsObj = [{
      id: '100',
      name: 'owl'
    }, {
        id: '102',
      name: 'dove'
    }, {
        id: '100',
      name: 'dove'
    }, {
        id: '102',
      name: 'owl'
    }];

    birdsObj = birdsObj.reduce((prev, cur) => [

      ...prev.filter((obj) => obj.name !== cur.name), cur

    ], []);

    console.log(birdsObj);

Output

    [{ 
        id: "100",
        name: "dove"
    },
    {
        id: "102",
        name: "owl"
    }]

Here, reduce() is used to iterate the array with current and previous elements, So filter() method will iterate the previous element array and check the previous element object value is matching against the current value.

– If a match is not found in the previous array object then the current object will be added to the previous array object.

– If matching is found in the previous array object then the value will be skipped and continues with next iteration.

At the end of the iteration, the previous array object with unique values will be returned.

JSfiddle

This tutorial is available in this JSFiddle.

Conclusion

In this tutorial, you’ve learned how to get all unique values in an array in Javascript. You’ve also known different ways to get all unique values in an array in Javascript.

If you’ve any questions, please comment below.

You May Also Like

Leave a Comment