Skip to content
Advertisement

Filter Object Array 1 on the basis on 2nd Object Array in Javascript(UnderscoreJS)

I wanted to filter Object Array 1 if it’s object value not exist in 2nd object Array. Non-Intersected values from 2nd array

> aaa = [{id:1, name:"abc"}, {id:2, name:"xyz"}], 
> bbb = [{group:1}, {group:4}]

> result should be [{id:2, name:"xyz"}]

_.filter(aaa, function(a){
    return _.find(bbb, function(b){
        return b.id !== a.group;
    });
});

But the result is using this code is wrong. please help me here

Advertisement

Answer

Here is a solution based on underscore.

b.id !== a.group -> a.id !== b.group to match your objects’ structure.

Then, a.id !== b.group -> a.id === b.group and negate the find result, to filter your object properly 😉

const aaa = [{id:1, name:"abc"}, {id:2, name:"xyz"}];
const bbb = [{group:1}, {group:4}];

const result = _.filter(aaa, function(a){
    return !_.find(bbb, function(b){
        return a.id === b.group;
    });
});

console.log(result);
<script src="https://underscorejs.org/underscore-min.js"></script>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement