Skip to content

Instantly share code, notes, and snippets.

@gdibble
Created May 12, 2017 22:41
Show Gist options
  • Save gdibble/8b831ef6a4cfa9786088541045abe7bd to your computer and use it in GitHub Desktop.
Save gdibble/8b831ef6a4cfa9786088541045abe7bd to your computer and use it in GitHub Desktop.
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