Created
May 12, 2017 22:41
-
-
Save gdibble/8b831ef6a4cfa9786088541045abe7bd to your computer and use it in GitHub Desktop.
Lodash mixin to find similar property values in an array of objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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