You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript 如何检查字符串数组中的triplicates三次重复值

如何检测字符串数组中的三次重复值

问题背景

需要从字符串数组中找出出现3次的重复值(triplicates),现有公开方案大多针对出现2次的重复值(duplicates)场景,无法直接复用。现有自实现代码如下,需验证正确性并提供更优实现:

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. 

方案解答

你的核心计数思路是正确的,样例运行能得到正确结果,但存在几个可优化的问题:

  • 函数直接在内部打印结果,耦合度高,无法灵活复用返回值
  • 用普通对象做计数、for...in遍历的写法存在原型链属性污染、特殊键名冲突的风险
  • 遍历全量统计所有值的出现次数,大数组场景下有可优化的性能空间

修正后的通用稳定版

用Map做计数避免键名冲突,将匹配结果作为返回值输出,兼容绝大多数场景:

const array = [
  "peace",
  "peace",
  "Vrede",
  "Patz",
  "Salam",
  "paz",
  "Salam",
  "Salam"
];

/**
 * 查找数组中恰好出现3次的字符串
 * @param {string[]} arr 待检测字符串数组
 * @returns {string[]} 符合条件的三次重复值集合
 */
const findTriplicates = (arr) => {
  const countMap = new Map();
  for (const str of arr) {
    countMap.set(str, (countMap.get(str) ?? 0) + 1);
  }
  return Array.from(countMap.entries())
    .filter(([, count]) => count === 3)
    .map(([value]) => value);
};

// 调用示例
const result = findTriplicates(array);
result.forEach(item => console.log(`${item} exists 3 times.`));
// 输出:Salam exists 3 times.

大数组性能优化版

如果待处理数组体量很大,不需要等全量遍历完成再统计,某个值计数到3时就可以直接标记为结果,后续重复遇到该值无需重复累加判断,减少无效运算:

const findTriplicatesFast = (arr) => {
  const countMap = new Map();
  const res = [];
  for (const str of arr) {
    const newCount = (countMap.get(str) ?? 0) + 1;
    countMap.set(str, newCount);
    if (newCount === 3) res.push(str);
  }
  // 如果需要严格匹配「恰好3次」,就打开下面这行过滤逻辑
  // return res.filter(str => countMap.get(str) === 3);
  // 默认返回「出现次数≥3次」的结果
  return res;
};

自定义调整说明

  • 若需要匹配出现次数大于等于3次的值,直接用上面的优化版即可,无需额外过滤
  • 若需要严格匹配恰好出现3次的值,用通用稳定版,或打开优化版里的过滤注释
  • 若数组中可能混入非字符串类型值,可在计数前增加类型判断,避免隐式类型转换导致的计数错误

内容的提问来源于stack exchange,提问作者omar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 00:24:23