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

Node.js中如何判断含重复元素的两个数组间的元素位置变化?

计算含重复元素数组的位置变化

我在Node.js应用中有两个数组array1和array2,二者均可能包含重复元素。我需要计算array1中每个元素相较于array2的位置变化。已知两个数组长度相同且包含的元素完全一致。位置变化定义为同一元素在两个数组中的索引差值。但由于数组可能包含重复元素,无法使用indexOf方法直接查找元素在array2中的索引,也不能使用字典。

示例数组:

const array1 = ['A', 'B', 'C', 'D', 'E', 'F', 'A'];
const array2 = ['A', 'B', 'E', 'C', 'D', 'A', 'F'];

在上述示例中,元素E的索引向后移动了2个位置,第二个A和F发生了交换。

以下是我参考相关思路后尝试实现的代码:

function collectPositionChange({ recent, result }, value, currentIdx) {
  // 在当前追踪的数组中查找元素的原索引
  const recentIdx = recent.indexOf(value);
  if (recentIdx !== currentIdx) {
    // 计算索引差值
    const idxDiff = currentIdx - recentIdx;

    // 记录位置变化信息
    result.push({
      value,
      currentIdx,
      recentIdx,
      idxDiff,
    });

    // 更新追踪数组,模拟元素移动后的状态
    recent.splice(recentIdx, 1); // 移除原位置的元素
    // 根据移动方向调整插入位置,插入到当前索引对应的位置
    recent.splice(currentIdx - (idxDiff > 0 ? 1 : 0), 0, value);

    // 输出位置变化的描述信息
    if (idxDiff < -1) {
      console.log(`元素'${value}'向后移动了${Math.abs(idxDiff)}个位置。`);
    } else if (idxDiff > 1) {
      console.log(`元素'${value}'向前移动了${Math.abs(idxDiff)}个位置。`);
    } else if (Math.abs(idxDiff) === 1) {
      const otherValue = recent[recentIdx];
      console.log(`元素'${value}'和'${otherValue}'发生了交换。`);
    }
  }
  return { recent, result };
}

// 测试用例
const array1 = ['A', 'B', 'E', 'C', 'D', 'A', 'F'];
const array2 = ['B', 'A', 'C', 'D', 'E', 'F', 'A'];

// 执行计算并打印结果(复制array2避免修改原数组)
console.log(
  array1
    .reduce(collectPositionChange, {
      recent: [...array2],
      result: []
    })
    .result
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:20:27