How to print the duplicate elements of an array in JavaScript

1 Answer

0 votes
function printDuplicates(arr) {
    const object = {};
 
    arr.forEach(function (item) {
        if (!object[item])
             object[item] = 0;
        object[item] += 1;
    })
 
    for (const val in object) {
           if (object[val] >= 2) {
              console.log(val);
           }
        }
}
 
const arr = [3, 5, 9, 1, 7, 8, 1, 9, 0, 3, 9];
 
printDuplicates(arr);
 
 
 
 
/*
run:

"1"
"3"
"9"
 
*/

 



answered May 3, 2020 by avibootz
edited Nov 18, 2022 by avibootz

Related questions

2 answers 211 views
1 answer 129 views
2 answers 163 views
1 answer 108 views
1 answer 125 views
1 answer 162 views
...