1

There are a few similar questions out there, but not quite one that answers what I need to do. I have 2 arrays, both filled with objects and nothing else.

arr1 = [
   {name:'one'},
   {name:'two'},
   {name:'three'},
]

arr2 = [
   {name:'four'},
   {name:'two'},
   {name:'six'},
]

What I want to do is return arr2 such that it doesn't have anything that matches in arr1. For example:

filteredArr = [
   {name:'four'},
   {name:'six'},
]

A requirement is I want to use array.prototype.filter to achieve this. My problem is, whenever I attempt to solve this, it gives me duplicates in my returned array. Here's what I've come up with:

Repl.it Link

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)

I know the logic of what it's doing and why I'm returning duplicates, but I don't know how to write it so that it simply returns state.two with all of the objects from state.one filtered out.

1 Answer 1

2

Use array#reduce with array#some. Iterate arr1 and check if the name value exists in the other array if it exists ignore it, otherwise add to your result array.

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.