Algorithms
Using array.reduce method to count duplicate elements
seoca
2022. 10. 23. 14:27
const alphabets = [1,1,1,2,3,3,1,4,5];
const counts = alphabets.reduce((acc, current) => {
if(acc[current]){
acc[current] += 1;
} else {
acc[current] = 1;
}
return acc;
}, {});
console.log(counts); //{ '1': 4, '2': 1, '3': 2, '4': 1, '5': 1 }