Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Lodash mixin to find similar property values in an array of objects
/**
* intersectionObj
* Pass an array of objects to find the similar objects
* You may also pass a single prop as a string, or an array of props to ignore
* Returns an array of the items which intersected
*
* Usage example:
* var arr = [ { id:1, b:2, c:3 }, { id:2, b:3, c:4 }, { id:3, b:2, c:3 } ];
* _.intersectionObj(arr, 'id');
* » [ { id:1, b:2, c:3 }, { id:3, b:2, c:3 } ]
*
* _.intersectionObj(arr, [ 'id', 'b' ]);
* » [ { id:1, b:2, c:3 }, { id:3, b:2, c:3 } ]
*/
/*global _*/ 'use strict';
var intersectionObj = function intersectionObj(array, props) {
var arraySansFirstItem = Array.prototype.slice.call(arguments, 1);
return _.filter(_.uniq(array), function (item) {
return _.every(arraySansFirstItem, function (other) {
return _.some(other, function (element) {
var a = props ? _.omit(_.clone(element), props) : element;
var b = props ? _.omit(_.clone(item), props) : item;
return _.isEqual(a, b);
});
});
});
};
_.mixin({ intersectionObj:intersectionObj });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment