[英]How can i find the duplicates in array of numbers + the counter how each number is repeated inside
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);
但是使用相同的代码,如果我尝试使用数字数组执行此操作,我会在
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. Object.keys
将键作为字符串返回,并且includes
类型相等性检查。
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
)注释行是我唯一更改的内容,并且您的代码工作正常(我在推入
duplicates
时转换为字符串,但您也可以在使用时修复它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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.