Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter out an array from another array [duplicate]

So I have 2 arrays of objects, it looks like this

    this.balanceCodes = [
        { ID: 1, StringValue: "dummy" },
        { ID: 2, StringValue: "data" }
    ];
    this.allCodes = [
        { ID: 1, StringValue: "dummy", Color: "red", Order: "low" },
        { ID: 2, StringValue: "data", Color: "green", Order: "medium" },
        { ID: 3, StringValue: "extra", Color: "black", Order: "low" },
        { ID: 4, StringValue: "options", Color: "grey", Order: "high" }
    ];

I want to filter out the objects that are in this.balanceCodes (based on ID)

So the desired result would be:

    this.result = [
        { ID: 3, StringValue: "extra", Color: "black", Order: "low" },
        { ID: 4, StringValue: "options", Color: "grey", Order: "high" }
    ];

how can I achieve this? I know I can easily filter out an object, but how can I do this for an entire array of objects?

I'm allowed to use Lodash.

like image 268
Nicolas Avatar asked Nov 28 '22 16:11

Nicolas


1 Answers

Use _.differenceBy() to find items in the 1st array (allCodes) that are not found in the 2nd array (balanceCodes):

var balanceCodes = [
    { ID: 1, StringValue: "dummy" },
    { ID: 2, StringValue: "data" }
];
var allCodes = [
    { ID: 1, StringValue: "dummy", Color: "red", Order: "low" },
    { ID: 2, StringValue: "data", Color: "green", Order: "medium" },
    { ID: 3, StringValue: "extra", Color: "black", Order: "low" },
    { ID: 4, StringValue: "options", Color: "grey", Order: "high" }
];

var result = _.differenceBy(allCodes, balanceCodes, 'ID');

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
like image 145
Ori Drori Avatar answered Nov 30 '22 22:11

Ori Drori