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

如何用更简洁高效的JS算法移除数组中为其他字符串子串的元素?

移除数组中作为其他字符串子串的元素:更简洁高效的实现

给定数组:['abc', 'defg', 'ab', 'jkl', 'ef'],需实现算法移除数组中所有是其他字符串子串的元素。其中'ab'是'abc'的子串,'ef'是'defg'的子串,预期结果为['abc', 'defg', 'jkl']。目前已实现如下代码:

const removeSubstrings = (input: string[]): string[] => {
    if (input.length < 2) return input;
    const result = [...input];
    let i = 0;
    while (i < result.length - 1) {
      let j = i + 1;
      while (j < result.length && j > i) {
        if (result[i].includes(result[j])) {
            result.splice(j, 1);
        } else if (result[j].includes(result[i])) {
            result.splice(i, 1);
            j--;
        } else {
          j++;
        }
      }
      if (j > i) {
        i++;
      }
    }
    return result;
  };

请问是否存在更简洁高效的算法(可使用JavaScript内置方法)?

肯定有,利用JavaScript的filter和some内置方法就能写出更简洁、可读性更强的实现,逻辑也更直观:

const removeSubstrings = (input) => {
  return input.filter(str => {
    // 只要数组里存在其他字符串包含当前字符串,就移除当前字符串
    return !input.some(otherStr => otherStr !== str && otherStr.includes(str));
  });
};

实现说明

  • filter:遍历数组,仅保留符合条件的元素
  • some:检查数组中是否存在任意一个不等于当前字符串的元素,且该元素包含当前字符串;如果存在,当前字符串就属于要移除的子串

对比原实现的优势

  1. 代码极简:用声明式数组方法替代嵌套while循环,行数大幅减少,一眼就能看懂逻辑
  2. 无索引混乱问题:原实现用splice修改数组会导致索引偏移,容易出bug;新实现返回全新数组,完全避开这个问题
  3. 可读性拉满:通过方法名就能理解代码意图,不需要跟踪复杂的i、j变量变化

测试验证

测试给定数组:

console.log(removeSubstrings(['abc', 'defg', 'ab', 'jkl', 'ef']));
// 输出:['abc', 'defg', 'jkl']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 18:38:07