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

如何将去除数组连续重复元素的Python循环转换为JavaScript实现?

在JavaScript中实现遍历数组并保留非连续重复元素

我们需要实现和你提供的Python代码完全一致的逻辑:遍历数组,仅保留与前一个元素不同的项,最终得到连续重复项被"压缩"的结果。

方法一:与Python逻辑完全对应的循环写法

这种写法最直观,和你给出的Python代码逻辑一一对应:

const arr1 = [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  7,  7,  0,  0,  0,  0,  0,  0,  0,
        13, 13,  0,  0,  0,  0,  0,  0,  0,  0, 13, 13,  0,  0,  0,  0,  0,  0,
         0,  0,  0, 15,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 14,  0,  0,
         0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  2,  0,
         0,  0];

const newLabels = [];
let previous = undefined; // 对应Python中的None

for (const l of arr1) {
    if (l !== previous) {
        newLabels.push(l);
        previous = l;
    }
}

console.log(newLabels);
// 输出结果:[0, 7, 0, 13, 0, 13, 0, 15, 0, 14, 0, 2, 0]

方法二:使用reduce的函数式写法

这是JavaScript中更简洁的函数式实现方式,利用数组的reduce方法完成累加:

const arr1 = [ /* 同上数组内容 */ ];

const newLabels = arr1.reduce((acc, current) => {
    // 若累加器为空,或当前元素与累加器最后一项不同,则添加
    if (acc.length === 0 || current !== acc[acc.length - 1]) {
        acc.push(current);
    }
    return acc;
}, []);

console.log(newLabels);
// 同样得到预期输出

两种写法都能实现需求:第一种逻辑清晰,适合新手理解;第二种代码更紧凑,符合JavaScript函数式编程的习惯。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 04:15:38