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.

Basic Example

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

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

    console.log(uniqueBirds );

Output

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

get all unique values in an array 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.

To get the unique values from an array,

  • Add the values to the set and convert the set back to an array.

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]

Code

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

    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

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.

    ["owl", "dove"]

get all unique values in an array Using Helper array[]

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

  • Create a new empty array
  • Iterate over the existing array and add the element to the new array if the new item is not existing in the array.
  • If it already exists, then ignore the current item.

By this way, you’ll have only the unique items in the array.

Code

The following code demonstrates how to use the for loop to get unique values in the array.

    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

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.

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

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

get all unique values in an array Using filter() + indexOf()

The Filter method is used to create a new array by applying the condition on the array. This is based on the ES5 standard, which most browsers support.

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.

Code

Let us see one example to get all unique values in an array using ES5.

    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"]

Code

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

    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"]

get all unique values in an array 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 the .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, 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]

get all unique values in an array Using filter() + sort()

You have to sort() the array first and arrange the values in order.
Next using.filter() method,

  • Iterate the sorted array
  • 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]

get all unique values in an array 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.

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.

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]

get all unique values in an array 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 of returning complete unique Javascript objects, not just the field.

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, the current object will be added to the previous array object.
  • If matching is found in the previous array object, the value will be skipped and continues with the next iteration.

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

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"
    }]

JSfiddle

This tutorial is available in this JSFiddle.

Additional Resources

Leave a Comment