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

如何用JavaScript数组方法识别数组中连续与非连续重复元素?

数组重复元素检测解决方案

需求说明

输入数组 ['USA', 'Australia', 'Australia', 'France', 'India', 'USA'],需根据以下规则输出结果:

  • 元素连续重复时,输出 Bingo 国家名
  • 元素非连续重复时,输出 Hooray 国家名
    预期输出:Bingo Australia、Hooray USA

同时需要支持动态遍历数组,能处理类似 ["Juan", "Maria", "Maria", "Juan"] 中索引0与3的非连续匹配场景。

现有代码问题

当前代码仅通过固定索引对比(如index + 1、index + 5)判断重复,无法动态检查后续所有非连续元素,扩展性极差。

改进实现代码

const countries = ['USA', 'Australia', 'Australia', 'France', 'India', 'USA'];
const processed = new Set(); // 记录已处理元素,避免重复输出

countries.forEach((value, index) => {
    // 跳过已处理过的元素
    if (processed.has(value)) return;

    // 检查连续重复:当前元素与下一个元素相等
    if (index < countries.length - 1 && countries[index] === countries[index + 1]) {
        console.log(`Bingo ${value}`);
        processed.add(value);
    } else {
        // 检查非连续重复:从当前索引+2的位置开始查找是否有相同元素
        const hasNonConsecutiveDuplicate = countries.slice(index + 2).includes(value);
        if (hasNonConsecutiveDuplicate) {
            console.log(`Hooray ${value}`);
            processed.add(value);
        }
    }
});

代码思路解析

  • 去重输出:使用Set存储已处理的元素,确保同一个国家只会被输出一次,避免连续重复时多次打印或非连续重复时重复匹配
  • 连续重复检测:直接对比当前索引与下一个索引的元素,同时判断索引边界,防止越界
  • 非连续重复检测:通过slice(index + 2)获取当前元素之后跳过紧邻位置的所有元素,再用includes方法快速判断是否存在重复,覆盖所有非连续的后续匹配场景

测试["Juan", "Maria", "Maria", "Juan"]数组时,会输出Bingo Maria和Hooray Juan,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 06:01:44