Array of object deep comparison with lodash

You can make use of differenceWith() with an isEqual() comparator, and invoke isEmpty to check if they are equal or not. var isArrayEqual = function(x, y) { return _(x).differenceWith(y, _.isEqual).isEmpty(); }; var result1 = isArrayEqual( [{a:1, b:2}, {c:3, d:4}], [{b:2, a:1}, {d:4, c:3}] ); var result2 = isArrayEqual( [{a:1, b:2, c: 1}, {c:3, d:4}], [{b:2, … Read more

How can I remove an element from a list, with lodash?

As lyyons pointed out in the comments, more idiomatic and lodashy way to do this would be to use _.remove, like this _.remove(obj.subTopics, { subTopicId: stToDelete }); Apart from that, you can pass a predicate function whose result will be used to determine if the current element has to be removed or not. _.remove(obj.subTopics, function(currentObject) … Read more

How to set specific property value of all objects in a javascript object array (lodash)

You don’t need lodash for this. The first object is missing your status property and it will be added. SHOWING THREE WAYS HOW YOU CAN DO IT IMMUTABLE VERSION (We create a new array using map) const arrImmutableVersion = arr.map(e => ({…e, status: “active”})); MUTABLE VERSIONS (We change the original array) arr.forEach((el)=>{el.status = “active”;}) or … Read more

How to use Lodash to merge two collections based on a key?

Second highest voted answer doesn’t do proper merge. If second array contains an unique property, it is not taken into account. This approach does a proper merge. Lodash var a = [ { userId:”p1″, item:1}, { userId:”p2″, item:2}, { userId:”p3″, item:4} ]; var b = [ { userId:”p1″, profile:1}, { userId:”p2″, profile:2}, { userId:”p4″, profile:4} … Read more

Using Lodash to sum values by key

This is a case of reduction for each unique element. I always use _.groupBy and then _.map the result to an array after applying the reduction. In this case the reduction operation is _.sumBy. var prjMgrValues = [ {“proj_mgr”:”Jack ProjManager”,”submitted_dollars”:12000}, {“proj_mgr”:”Jack ProjManager”,”submitted_dollars”:750000}, {“proj_mgr”:”Joe ProjManager”,”submitted_dollars”:45000} ]; var output = _(prjMgrValues) .groupBy(‘proj_mgr’) .map((objs, key) => ({ ‘proj_mgr’: … Read more

Using lodash to compare jagged arrays (items existence without order)

If you sort the outer array, you can use _.isEqual() since the inner array is already sorted. var array1 = [[‘a’, ‘b’], [‘b’, ‘c’]]; var array2 = [[‘b’, ‘c’], [‘a’, ‘b’]]; _.isEqual(array1.sort(), array2.sort()); //true Note that .sort() will mutate the arrays. If that’s a problem for you, make a copy first using (for example) .slice() … Read more