有一些类似的问题,但不是一个能回答我需要做的事情。我有2个数组,都填充了对象,没有别的。
arr1 = [
{name:'one'},
{name:'two'},
{name:'three'},
]
arr2 = [
{name:'four'},
{name:'two'},
{name:'six'},
]
我想要做的是返回arr2,使其在arr1中没有匹配的内容。例如:
filteredArr = [
{name:'four'},
{name:'six'},
]
一个要求是我想使用array.prototype.filter来实现这一点。我的问题是,每当我尝试解决这个问题时,它都会在我返回的数组中给出重复项。以下是我的想法:
let state = {
one: [
{name:'one'},
{name:'two'},
{name:'three'}
],
two: [
{name:'one'},
{name:'four'},
{name:'five'},
{name:'three'}
]
}
let {one, two} = state
let newStuff = []
two.filter(s => {
one.filter(t => {
s.name !== t.name ? newStuff.push(s) : null
})
})
console.log(newStuff)
我知道它正在做什么的逻辑以及为什么我要返回重复项,但是我不知道如何编写它以便它只返回state.two并且state.one中的所有对象都被过滤掉了。 / p>
答案 0 :(得分:2)
将array#reduce
与array#some
一起使用。迭代arr1
并检查另一个数组中是否存在name
值,如果存在则忽略它,否则添加到结果数组中。
var arr1 = [ {name:'one'}, {name:'two'}, {name:'three'}],
arr2 = [ {name:'four'}, {name:'two'}, {name:'six'}],
result = arr2.reduce((r,{name}) => !arr1.some(o => o.name === name) ? (r.push({name}), r) : r, []);
console.log(result);