首页 > 解决方案 > 如果字符串存在于javascript中的其他元素中,我想从字符串数组中删除一个元素

问题描述

我希望能够删除数组中的元素,如果它出现在或包含在同一数组中的任何其他元素中。

例如:

const arr = ["Hello" , "Hell" , "Lower" , "Low", "Hii"];

目标输出:

["Hello" , "Lower", "Hii]

标签: javascript

解决方案


使用数组Array.prototype.find()Array.prototype.includes()Set的一种方法,

const arr = ["Hello", "Hell", "Lower", 'Lo', "Low", "Hii"];
const expected = [];
arr.forEach(function(element) {
  el = arr.find(a => a.includes(element));
  expected.push(el);
})

console.log([...new Set(expected)]);


推荐阅读