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

如何实现:数组中unit重复时返回其起止索引?现有代码存问题

问题:获取有序数组中重复unit的起止索引

我需要从下方的有序数组中,获取每个重复unit元素的起止索引。比如unit 39是从索引1重复到索引3,对吧?

原数组:

const array = [
  {
    unit: 38,
  },
  {
    unit: 39,
  },
  {
    unit: 39,
  },
  {
    unit: 39,
  },
  {
    unit: 40,
  },
  {
    unit: 41,
  },
  {
    unit: 41,
  },
  {
    unit: 42,
  },
]

期望结果:

[
  {
    unit: 39,
    fromIndex: 1,
    toIndex: 3,
  },
  {
    unit: 41,
    fromIndex: 5,
    toIndex: 6,
  },
]

我试过记录每对unit的索引,但这种方法处理不了重复次数超过两次的情况,我的代码片段如下:

let u;

for (let i = 0; i < array.length; i++) {
  const a = array[i];
  const b = array[i + 1] || {
    unit: null
  };

  if (a.unit == b.unit) {
    u = a.unit; // remmeber the repeated unit here
    ...
  }
}

解决方案

因为数组是有序的,我们可以通过跟踪当前重复单元的起始索引来实现需求,具体代码如下:

const array = [
  { unit: 38 },
  { unit: 39 },
  { unit: 39 },
  { unit: 39 },
  { unit: 40 },
  { unit: 41 },
  { unit: 41 },
  { unit: 42 },
];

const result = [];
if (array.length === 0) {
  console.log(result);
  return;
}

let currentUnit = array[0].unit;
let startIndex = 0;

for (let i = 1; i < array.length; i++) {
  const unit = array[i].unit;
  // 遇到不同单元时,检查之前的单元是否有重复
  if (unit !== currentUnit) {
    if (i - 1 > startIndex) { // 起始索引小于当前前一个索引,说明有重复
      result.push({
        unit: currentUnit,
        fromIndex: startIndex,
        toIndex: i - 1
      });
    }
    // 更新当前跟踪的单元和起始索引
    currentUnit = unit;
    startIndex = i;
  }
}

// 处理最后一组可能的重复单元
if (array.length - 1 > startIndex) {
  result.push({
    unit: currentUnit,
    fromIndex: startIndex,
    toIndex: array.length - 1
  });
}

console.log(result);

代码说明

  • 先初始化结果数组,以及跟踪当前单元和起始索引的变量
  • 从数组第二个元素开始遍历,对比当前元素和跟踪的单元
  • 遇到不同单元时,判断之前的单元是否存在重复:如果起始索引小于当前元素的前一个索引,就说明有重复,把起止信息存入结果数组
  • 遍历结束后,还要检查最后一组元素是否有重复,避免遗漏
  • 最终result数组就是你需要的格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 08:35:40