This question already has answers here:
Closed 2 years ago.
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.
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>
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);
_.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 })
}