I need to find duplicates that are inside array more or equal to two times. If i have array of strings for example this would work
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);
c.log(r.duplicates);
c.log(r.counter);
as i result i get in the console
["as", "i", "do"]
{i: 2, do: 2, as: 3}
but with this same code if i try to do this with array of numbers i get {} in the c.log(r.counter);
i don't know why includes is not working with the numbers in this case
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);
c.log(r.duplicates);
c.log(r.counter);
so in the console i get
[9, 4, 7]
{}
Object.keys
returns the keys as strings, and includes
checks for type equality too.
The commented line is the only thing I changed and your code is working fine (I am casting to string when pushing into duplicates
but you can also fix it while using includes
)
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}`). // casting to string } } } 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.