JavaScript count the duplicates in an array Edit

Murugan Andezuthu Dharmaratnam | 08 August 2022 | 153

Post has been modified and is pending approval by an admin or moderator

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   "
"); document.write("Banana: " counts.banana "
"); document.write("Orange: " counts.orange "
");