The task is to write a function that finds a number of items appearing more than once in an array.
For example:
countIdentic([3, 3, 7, 7, 3, 3, 4, 5, 5, 8, 8, 8]) returns 4
countIdentic([15,14,13,19,13,14,14,14,7,9,9]) returns 3
I already have a solution but I find it complicated. So maybe there is a more elegant solution to that task?
function countIdentic(arr) {
var clone = arr.slice(0),
test = [],
cur,
count = 0;
while (clone.length) {
cur = clone.shift();
if (test.indexOf(cur) === -1) {
test.push(cur);
if (clone.indexOf(cur) >= 0) {
count++;
}
}
}
return count;
}
console.log( countIdentic([3, 3, 7, 7, 3, 3, 4, 5, 5, 8, 8, 8]) );
console.log( countIdentic([15,14,13,19,13,14,14,14,7,9,9]) );
You can use Set, so you don't iterate many times over the original array. But that will take some more space complexity :)
Space complexity: O(n), where n is arr.length. Since seenOnce and duplicates can grow up to arr.length size.
Time complexity: O(n), where n is arr.length. Since we iterate over the arr only once.
function countIdentic(arr) {
const seenOnce = new Set();
const duplicates = new Set();
arr.forEach((item) => {
if (duplicates.has(item)) {
return;
}
if (seenOnce.has(item)) {
duplicates.add(item);
seenOnce.delete(item);
return;
}
seenOnce.add(item);
});
return duplicates.size;
}
console.log(countIdentic([3, 3, 7, 7, 3, 3, 4, 5, 5, 8, 8, 8]));
console.log(countIdentic([15, 14, 13, 19, 13, 14, 14, 14, 7, 9, 9]));
function countIdentic(arr) {
return [... // get number of occurences for every item
arr.reduce((map, num) => map.set(num, (map.get(num) ?? 0) + 1), new Map)
.entries()
]
// filter pairs with more than one occurence
.filter(([num, count]) => count > 1)
// get the count
.length;
}
console.log( countIdentic([3, 3, 7, 7, 3, 3, 4, 5, 5, 8, 8, 8]) );
console.log( countIdentic([15,14,13,19,13,14,14,14,7,9,9]) );