How to use the reduce() Method In Javascript
The reduce() method can be used to create a frequency map of the elements in the array. Once we have this map, we can filter out the elements that appear only once.
Example: In this example, we will use the reduce() method to create a frequency map and then filter out the non-unique values using the filter() method.
const array = [1, 2, 2, 3, 4, 5, 6, 6, 7, 8, 8, 8];
console.log("Before filtering non unique values: " + array);
const frequencyMap = array.reduce((acc, value) => {
acc[value] = (acc[value] || 0) + 1;
return acc;
}, {});
const unique = array.filter(value => frequencyMap[value] === 1);
console.log("After filtering non unique values: " + unique);
Output
Before filtering non unique values: 1,2,2,3,4,5,6,6,7,8,8,8 After filtering non unique values: 1,3,4,5,7
How to filter out the non-unique values in an array using JavaScript ?
In JavaScript, arrays are the object using the index as the key of values. In this article, let us see how we can filter out all the non-unique values and in return get all the unique and non-repeating elements.
These are the following ways by which we can filter out the non-unique values in an array:
Table of Content
- Using the filter() method
- Using for loop
- Using Set and filter
- Using the reduce() Method