How to Get Only Unique Values From Array in JavaScript

How to get only unique values from array in JavaScript. In this tutorial, you will learn how to get unique values from json array in javascript with examples.

This example will teach you three javascript methods or functions to get unique values from arrays in JavaScript ES6.

Three methods to get unique values from arrays in ES6

  • Using Set
  • Using Array.filter
  • Using Iteration

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.

Let’s see the example:

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

Using Array.filter

In this example, you will learn array. filter method of javascript. 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]

Using Iteration

In this example, you will learn how to get unique values from array using iteration. The for…of loop to iterate through the array and keep only unique elements in a new array.

Let’s see the example:

<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.

Recommended JavaScript Tutorials

Related Posts