Is there a way to find duplicates in an array that appear two or more times? For example, if I have an array of strings like this:
var arrStr = 'i do as as becasue i do as';
function CheckDuplicates(sentence)
{
let arr = sentence.split(" ");
let counter = {};
let duplicates = [];
for(let i = 0;i < arr.length;i++)
{
let item = arr[i];
counter[item] = counter[item] >= 1 ? counter[item] += 1 : 1;
if(item != "")
{
if(counter[item] == 2)
{
duplicates.push(item);
}
}
}
Object.keys(counter)
.filter(key => !duplicates.includes(key))
.forEach(k => delete counter[k]);
return {
duplicates: duplicates,
counter: counter
};
}
let r = CheckDuplicates(arrStr);
console.log(r.duplicates);
console.log(r.counter);
The console output would be:
["as", "i", "do"]
{i: 2, do: 2, as: 3}
However, when trying the same code with an array of numbers, the result is not as expected:
It shows {} in the console.log(r.counter);
Seems like the includes method does not work correctly with numbers. Here's an example with an array of numbers:
var arr = [9, 9, 9 ,111, 2, 3, 4, 4, 5, 7 , 7];
function CheckDuplicates(sentence)
{
let counter = {};
let duplicates = [];
for(let i = 0;i < arr.length;i++)
{
let item = arr[i];
counter[item] = counter[item] >= 1 ? counter[item] += 1 : 1;
if(item != "")
{
if(counter[item] == 2)
{
duplicates.push(item);
}
}
}
Object.keys(counter)
.filter(key => !duplicates.includes(key))
.forEach(k => delete counter[k]);
return {
duplicates: duplicates,
counter: counter
};
}
let r = CheckDuplicates(arr);
console.log(r.duplicates);
console.log(r.counter);
This will result in:
[9, 4, 7]
{}