JavaScript筛选方法,从数组中删除所有匹配值的项

3
我试图使用数组数值匹配来移除所有项目,但是只有一个项目被移除了。如何使用 filter 方法移除所有项目或者实现此操作的最佳方法是什么?
let data = [
    {
        id: '1',
        title: 'ABC'
    },
    {
        id: '2',
        title: 'DEF'
    },
    {
        id: '3',
        title: 'GHI'
    },
    {
        id: '4',
        title: 'JKL'
    },
    {
        id: '5',
        title: 'MNO'
    }
]


data = data.filter(post => {

    let remove = ['2', '4', '5']

    for(let i = 0; i < remove.length; i++) {
        return post.id !== remove[i]
    }

})

console.log(data)

谢谢

4个回答

3
如果你想从数组中移除元素,那么应该返回false。

let data = [
    {
        id: '1',
        title: 'ABC'
    },
    {
        id: '2',
        title: 'DEF'
    },
    {
        id: '3',
        title: 'GHI'
    },
    {
        id: '4',
        title: 'JKL'
    },
    {
        id: '5',
        title: 'MNO'
    }
]
let remove = ['2', '4', '5']

data = data.filter(post => {
return !remove.includes(post.id);
})

console.log(data)


3
所有通知都在代码片段的注释中。

let data = [ { id: '1', title: 'ABC' }, { id: '2', title: 'DEF' }, { id: '3', title: 'GHI' }, { id: '4', title: 'JKL' }, { id: '5', title: 'MNO' } ]

const remove = ['2', '4', '5']

// `indexOf` is from ES5
data = data.filter(post => remove.indexOf(post.id) === -1)
console.log(data)

// `includes` is from ES7
data = data.filter(post => !remove.includes(post.id))
console.log(data)

// this will recreate the array ['2', '4', '5'] 5 times
data = data.filter(post => !['2', '4', '5'].includes(post.id))
console.log(data)


2

filter 中使用 for 循环是没有必要的。

相反,可以在 filter 中使用 some 方法。 some 方法检查提供的函数中是否至少有一个元素满足条件。这样就可以避免不必要的迭代:

data.filter(f => !remove.some(s => s == f.id))

一个例子:

let data = [
    {
        id: '1',
        title: 'ABC'
    },
    {
        id: '2',
        title: 'DEF'
    },
    {
        id: '3',
        title: 'GHI'
    },
    {
        id: '4',
        title: 'JKL'
    },
    {
        id: '5',
        title: 'MNO'
    }
]

let remove = ['2', '4', '5']

console.log(data.filter(f => !remove.some(s => s == f.id)));


1
我建议使用includes而不是嵌套的for循环。
你还应该将remove变量移到循环外,这样它就不会每次重新初始化。 filter方法的回调函数是一个predicate。如果条件评估为true,则迭代中的当前值将被返回。在您的情况下,如果当前值不在删除数组中,则应返回。

let data = [
  {
      id: '1',
      title: 'ABC'
  },
  {
      id: '2',
      title: 'DEF'
  },
  {
      id: '3',
      title: 'GHI'
  },
  {
      id: '4',
      title: 'JKL'
  },
  {
      id: '5',
      title: 'MNO'
  }
]

const remove = ['2', '4', '5']

data = data.filter(post => {
  return !remove.includes(post.id)
})

console.log(data)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接