s

JavaScript count the duplicates in an array edit button Edit

author
Murugan Andezuthu Dharmaratnam | calendar 08 August 2022 | 616

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 "
");