代码之家  ›  专栏  ›  技术社区  ›  Dave

JavaScript如何从一个数组中删除第二个数组中包含的元素[duplicate]

  •  0
  • Dave  · 技术社区  · 6 年前

    我误解了如何删除一个数组中的一个元素,该数组中有一个匹配的元素到另一个数组。

    例子:

    const items = ['first', 'second', 'third']
    const secondItems = ['first', 'second']
    

    console.log(items) | 'third'
    console.log(secondItems) | 'first', 'second
    

    用two-forEach或filter和checking语句尝试了很多次,但总是得到错误的结果。

    3 回复  |  直到 6 年前
        1
  •  1
  •   Dacre Denny    6 年前

    这可以通过以下方法解决:

    const items = ['first', 'second', 'third'];
    const secondItems = ['first', 'second'];
    
    
    const filteredBySecondItems = items.filter(function(item) {
    
      // For item in items array, check if there is a match
      // in secondItems. If there is no match, allow it
      // to be included in the returned list
      return secondItems.indexOf(item) === -1 
    
    })
    
    console.log(filteredBySecondItems) // [ 'third' ]
        2
  •  2
  •   connexo    6 年前

    简单使用 Array.prototype.filter()

    const items = ['first', 'second', 'third']
    const secondItems = ['first', 'second']
    
    console.log(items.filter(i => !secondItems.includes(i)))
    console.log(secondItems.filter(i => items.includes(i)))

    但我并不完全理解你的期望:

    console.log(secondItems) | 'first', 'second
    

    你能在评论中详细说明一下吗?

        3
  •  1
  •   mp92    6 年前
    items.filter(x => !secondItems.includes(x))