简体   繁体   中英

Using ES5/Lodash, how can I find/remove objects in one array that aren't in another without comparing the whole object?

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM