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

TypeScript向数组push元素时基于指定下标值实现数组去重的方法

实现方案

你可以通过数组的some方法做重复校验,匹配到符合条件的重复项就跳过推入,具体修改如下:

基础版(适合中小数据量)

let array1: any[] = [];
let array2: any[] = [];

for (let count= 0; count < sheet.length; count++) {
  array2 = [sheet[count][0],sheet[count][1],sheet[count][2], sheet[count][3],sheet[count][4]];
  // 校验array1中是否存在第0、3位同时相等的元素
  const hasDuplicate = array1.some(existItem => {
    return existItem[0] === array2[0] && existItem[3] === array2[3]
  })
  // 无重复才推入
  if (!hasDuplicate) {
    array1.push(array2); 
  }
}

some方法会遍历数组中的元素,只要有一个元素满足判断条件就会立刻返回true,不用遍历完整数组,性能优于全量遍历。

优化版(适合超大数据量)

如果你的sheet行数非常多,基础版每次校验都要遍历array1,时间复杂度为O(n²),可以用Set存储已出现的唯一标识,把校验复杂度降到O(1):

let array1: any[] = [];
// 存储已出现的「第0位+第3位」组合标识
const existCombination = new Set();

for (let count= 0; count < sheet.length; count++) {
  const array2 = [sheet[count][0],sheet[count][1],sheet[count][2], sheet[count][3],sheet[count][4]];
  // 生成唯一key,建议用不会出现在业务值中的字符做分隔符
  const currentKey = `${array2[0]}||${array2[3]}`;
  if (!existCombination.has(currentKey)) {
    existCombination.add(currentKey);
    array1.push(array2);
  }
}

如果第0位、第3位的值可能包含你选的分隔符,可以改用JSON.stringify([array2[0], array2[3]])生成key,避免冲突。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 11:06:04