How to use reduce() and an object to count occurrences In Javascript
Using reduce() and an object to count occurrences involves initializing an empty object to store counts. The array is iterated with reduce(), updating counts in the object. Non-unique values are collected based on their count
Example: In this example we use reduce() and an object to count occurrences of array elements, capturing non-unique values when their count reaches 2.
let array = [1, 2, 3, 2, 4, 5, 1];
let count = {};
let nonUniqueValues = array.reduce((acc, value) => {
count[value] = (count[value] || 0) + 1;
if (count[value] === 2) acc.push(value);
return acc;
}, []);
console.log(nonUniqueValues);
Output
[ 2, 1 ]
JavaScript Get all non-unique values from an array
We have given a JavaScript array, and the task is to find all non-unique elements of the array. To get all non-unique values from the array here are a few examples.
These are the following methods to get all non-unique values from an array:
Table of Content
- Using Array Slice() Method
- Using for loop
- Using filter() Method
- Using indexOf() Method
- Using reduce() and an object to count occurrences: