If you have any array or JSON array. Some values are duplicated in that. But you want to keep unique values in the array or JSON array. 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 or json arrays in JavaScript ES6.
How to Get Unique Values From Array in JavaScript
There are a few approaches to getting unique values from a array or JSON array in JavaScript. Here are a few of the most common methods and their examples to achieve this:
- Using Set
- Using Array.filter
- Using Reduce
Using Set
A Set is like a special container that only keeps unique items. To find the unique items in an array, just put the array into a Set, and then change it back to an array. Look at this 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
The filter() method is like a helper that checks each item in the group and selects only those that meet a certain condition. So, if we want to get only those particular items that appear once in the list (no repetitions), we can use filter(). Here is a simple 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
The reduce()
method is like a helper that works through each item in a list, doing something with each item and accumulating a single result. To remove duplicates from an array, you can use reduce()
to turn the array into a Set, which only keeps unique values. After that, you change it back to an array. Here’s how you can do it:
const arr = [1, 2, 3, 1, 2];
const uniqueValues = arr.reduce((uniqueValues, value) => {
if (!uniqueValues.includes(value)) {
uniqueValues.push(value);
}
return uniqueValues;
}, []);
console.log(uniqueValues); // [1, 2, 3]
Output:
[1, 2, 3]
Conclusion
In this example tutorial, you have learned three methods of javascript to get only unique values from array or json array.