s

JavaScript count the duplicates in an array edit button Edit

author
Murugan Andezuthu Dharmaratnam | calendar 08 August 2022 | 1170

I found this easiest 3 line to code to count duplicates in an array and it works.

Solution Count Duplicates In An Array



var elements = ["apple", "apple", "orange", "apple", "banana"];

var counts = {};

elements.forEach(function(x) {
    counts[x] = (counts[x] || 0)   1;
});

document.write("Apple: "   counts.apple   "<br/>");
document.write("Banana: "   counts.banana   "<br/>");
document.write("Orange: "   counts.orange   "<br/>");