JavaScript Get Unique Values From Array

To get unique values from array in JavaScript; Through this tutorial, i am going to show you how to get unique values from array or json array in JavaScript with the help of examples.

JavaScript Get Unique Values From Array

There are three methods to get unique values from array or json array in JavaScript:

  • JavaScript Get Unique Values From Array Using Set
  • JavaScript Get Unique Values From Array Using Array.filter
  • JavaScript Get Unique Values From Array Using Iteration

JavaScript Get Unique Values From Array Using Set

In ES6, a Set is a collection of unique values. If you can pass an array into a Set, it return unique values. As shown below:

<script>
const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30]
const uniqueAges = [...new Set(ages)]
console.log(uniqueAges)
</script>

Output:

[26, 27, 28, 29, 30]

JavaScript Get Unique Values From Array Using Array.filter

Using the javaScript filter method to get or find unique values from array; the Array.filter function takes a callback whose first parameter is the current element in the operation. It also takes an optional index parameter and the array itself.

Let’s see the example:

<script>
const arr = [2019, 2020, 2019, 2018, 2020, 2021, 2030, 2020, 2019];
// Using Array.filter
const useFilter = arr => {
  return arr.filter((value, index, self) => {
    return self.indexOf(value) === index;
  });
};
const result = useFilter(arr);
console.log(result);
</script>

Output:

[2019, 2020, 2018, 2021, 2030]

JavaScript Get Unique Values From Array Using Iteration

Using iteration with for of loop; you can get unique values from array. As shown below:

<script>
const arr = [2019, 2020, 2019, 2018, 2020, 2021, 2030, 2020, 2019];
const useIteration = arr => {
  const map = [];
  for (let value of arr) {
    if (map.indexOf(value) === -1) {
      map.push(value);
    }
  }
  return map;
};
const result = useIteration(arr);
console.log(result);
</script>

Output:

 [2019, 2020, 2018, 2021, 2030]

Conclusion

In this example tutorial, you have learned three methods of javascript forget only unique values from array.

More JavaScript Tutorials

Recommended:-JavaScript Arrays

Leave a Comment