检查“一式三份” JavaScript数组中的字符串
试图找到最佳检查一式三份值的最佳方法在一系列字符串中。
我找到了许多用于重复值的Stackoverflow解决方案,在这里并非如此。
这是我解决此问题最能获得的,我不确定这是正确的方法:
const array = [
"peace",
"peace",
"Vrede",
"Patz",
"Salam",
"paz",
"Salam",
"Salam"
];
const findTriplicates = (param) => {
let counts = {};
for (let i = 0; i < param.length; i++) {
if (counts[param[i]]) {
counts[param[i]] += 1;
} else {
counts[param[i]] = 1;
}
}
for (let i in counts) {
if (counts[i] === 3) {
console.log(i + " exists " + counts[i] + " times.");
}
}
};
findTriplicates(array); // Salam exists 3 times.
请不要犹豫修复我的代码或发布您的解决方案 。
感谢您提前的支持:)
欢呼!
trying to find the best way to check for triplicates values inside an array of strings.
I found many stackoverflow solutions for duplicates values which is not the case in here.
This is the farest i could get with solving this and I am not sure if it is the correct way:
const array = [
"peace",
"peace",
"Vrede",
"Patz",
"Salam",
"paz",
"Salam",
"Salam"
];
const findTriplicates = (param) => {
let counts = {};
for (let i = 0; i < param.length; i++) {
if (counts[param[i]]) {
counts[param[i]] += 1;
} else {
counts[param[i]] = 1;
}
}
for (let i in counts) {
if (counts[i] === 3) {
console.log(i + " exists " + counts[i] + " times.");
}
}
};
findTriplicates(array); // Salam exists 3 times.
please don't hesitate to fix my code or to post your solution.
thanks for your support in advance :)
Cheerz!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的总体想法很好,使用哈希地图(JS对象)是完成该任务的最佳选择。
您可以将“ === 3”检查到第一个循环,并有另一个可以节省一式三份的对象,它将快两倍。
Your overall idea is good, using Hash Maps (js objects) is the best option for the task.
You can move your "=== 3" check to the first loop and have another object to save triplicates, it will be twice faster.
检查一下
check this out
没有正确的方法可以做这样的事情。您总是可以优化或牺牲性能以实现可读性,但这取决于开发人员。
我对FindTriplicates的功能没有任何更改,但是代码却大不相同。
FindTriplicates2的工作方式有所不同,但绝不是优越的
There is no correct way to do things like this. You can always optimize or sacrifice performance for readability, but that is up to the developer.
I changed nothing about the functionality in findTriplicates, but the code is very different.
findTriplicates2 works a little different but is by no means superior
您可以创建一个对象,以保留字符串重复的次数,然后在数组中的每个元素中迭代,同时更新对象中的计数。然后,您通过该对象过滤,以等于3的任何值。
You create an object to keep count of how many times the string repeats and then iterate through each element in the array while updating the count in the object. Then you filter through that object for any values equal to 3.