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

如何将非连续索引的对象数组改为连续递增索引?

如何将稀疏数组转换为索引连续的数组?

你可以通过以下几种简洁的方式,把稀疏数组(索引不连续)转换成索引从0开始连续递增的数组:

方法1:使用展开运算符 ...

展开运算符会自动忽略稀疏数组中的空槽,直接生成连续索引的新数组:

// 你的稀疏数组
const sparseArray = [
  {slot_id: 'slot_8848241006_1657877963_1657886201'},
  ,
  {slot_id: 'slot_8848241006_1657877963_1657886978'},
  ,
  {slot_id: 'slot_9495414200_1657194770_1657877482'},
  ,
  {slot_id: 'slot_9495414200_1657194770_1657886410'},
  ,
  {slot_id: 'slot_9495414200_1657194770_1657886563'}
];

// 转换为连续索引数组
const continuousArray = [...sparseArray];
console.log(continuousArray);

方法2:使用 Array.filter()

过滤掉数组中值为undefined的空槽项:

const continuousArray = sparseArray.filter(item => item !== undefined);

方法3:使用 Array.from()

Array.from()会遍历数组的可迭代元素,自动跳过空槽生成连续数组:

const continuousArray = Array.from(sparseArray);

方法4:使用 Array.reduce()

手动收集非空元素,构建新数组:

const continuousArray = sparseArray.reduce((result, current) => {
  if (current !== undefined) {
    result.push(current);
  }
  return result;
}, []);

以上方法都会返回一个新数组,原稀疏数组不会被修改。所有方法处理后,数组的索引都会从0开始连续递增,符合你需要的格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 20:57:17