Reputation: 1257
Say I have two arrays of objects....
var oldProducts = [{id: "prod1", time: 10 clicks: 1342}, {id: "prod2", time: 3, clicks: 231289}, {id: "prod3", price: "$10", time: 0, clicks: 84238}];
var newProducts = [{id: "prod1", time 10, clicks: 0}, {id: "prod3", time: 3, clicks: 0}];
I want to find if a product in oldProducts
is not in newProducts
, based on the id and remove it.
I don't want to compare the entire object, as the products coming in can be different than the ones existing with some properties....but they shouldn't be removed.
My first thoughts are to use _.map
on both and _.filter
to find the tags in oldProducts
to remove....and then remove those products from newProducts
.
I feel though...it could be simpler than that though. Two maps, one filter, then I guess iterating over the newProducts again is a lot of iterations over n.
I can't use ES6.....unfortunately.
Upvotes: 0
Views: 219
Reputation: 191976
You can use lodash's _.differenceBy()
and use id
as the iteratee. The _.differenceBy()
function returns a new array with items in the 1st array, that don't exist in the 2nd array. The iteratee is a function or a string, that will be used the get the values that the items would be compared with to decide if they are identical.
var oldProducts = [{id: "prod1", time: 10, clicks: 1342}, {id: "prod2", time: 3, clicks: 231289}, {id: "prod3", price: "$10", time: 0, clicks: 84238}];
var newProducts = [{id: "prod1", time: 10, clicks: 0}, {id: "prod3", time: 3, clicks: 0}];
var result = _.differenceBy(oldProducts, newProducts, 'id');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
If you want to change the 1st array (oldProducts
in this case) use _.pullAllBy()
instead:
var oldProducts = [{id: "prod1", time: 10, clicks: 1342}, {id: "prod2", time: 3, clicks: 231289}, {id: "prod3", price: "$10", time: 0, clicks: 84238}];
var newProducts = [{id: "prod1", time: 10, clicks: 0}, {id: "prod3", time: 3, clicks: 0}];
var result = _.pullAllBy(oldProducts, newProducts, 'id');
console.log(oldProducts);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
Upvotes: 1