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

如何获取原数组指定索引元素在打乱后新数组中的索引

方案1:数组元素无重复时直接按值查找

你只需要先取出原数组指定索引对应的目标元素,再到打乱后的数组中查找该元素的索引即可,示例代码如下:

const first = ['a','b','c'];
const index = 1;
const shuffled = ['c','a','b'];

// 1. 取原索引对应的目标元素
const target = first[index];
// 2. 查找目标元素在打乱后数组的索引
const newIndex = shuffled.indexOf(target);

console.log(newIndex); // 输出 2,符合预期

方案2:数组存在重复元素时,用原索引绑定的方式查找

如果数组中有重复值,无法通过值本身区分元素,你可以在打乱数组前先给每个元素绑定对应的原索引,打乱后直接按原索引匹配即可:

const first = ['a','b','c', 'b']; // 存在重复元素b
const index = 1; // 原索引1对应的是第一个b
// 给每个元素绑定原索引
const firstWithMark = first.map((val, originalIdx) => ({ val, originalIdx }));

// 打乱数组的逻辑针对firstWithMark操作,得到打乱后的数组
const shuffledWithMark = [
  {val: 'c', originalIdx: 2},
  {val: 'b', originalIdx: 3},
  {val: 'a', originalIdx: 0},
  {val: 'b', originalIdx: 1}
];

// 按原索引匹配查找新索引
const newIndex = shuffledWithMark.findIndex(item => item.originalIdx === index);
console.log(newIndex); // 输出 3,准确定位到原索引1对应的元素

注意事项

  • indexOf和findIndex方法找不到匹配项时都会返回-1,你可以根据业务需要添加异常判断逻辑。
  • 非基础类型元素(比如对象、数组)不能直接用indexOf匹配,推荐统一用方案2的标记方式处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:06:03