Filter out an array from another array [duplicate]

2020-04-16 17:38发布

问题:

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.

回答1:

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>



回答2:

You can achieve this by using filter and every, without having to use lodash:

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 = allCodes.filter((code) => 
  balanceCodes.every((balanceCode) => balanceCode.ID !== code.ID));

console.log(result);



回答3:

_.remove would be your best bet. If the IDs are unique - something like this should suffice (using lodash):

for( let balanceCode of balanceCodes){
    _.remove( allCodes, (code) => { code.ID === balanceCode.ID })
}