这个问题在这里已有答案:
我误解了如何删除数组中具有匹配元素的元素到另一个数组。
例:
const items = ['first', 'second', 'third']
const secondItems = ['first', 'second']
预期:
console.log(items) | 'third'
console.log(secondItems) | 'first', 'second
希望一些例子如何实现。尝试了两次forEach或过滤和检查语句,但我总是得到错误的结果。
这可以通过以下方式解决:
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' ]
只需使用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
你能在评论中详细说明吗?
items.filter(x => !secondItems.includes(x))
刚尝试在浏览器控制台中运行。