jquery - Get only common objects from a list of arrays in javascript -
i have couple arrays in javascript code (i'm using knockout js too) , want single array contains common objects of arrays.
my code this:
array1 = [{a: 1, b: 'something'}, {a: 2, b: 'something1'},{a: 3, b: 'something3'}]; array2 = [{a: 3, b: 'something3'}, {a: 1, b: 'something'}, {a: 4, b: 'something4'}] array2 = [{a: 3, b: 'something3'}, {a: 1, b: 'something'}, {a: 5, b: 'something5'}]
so, arrays want common of 1 single array, result this:
array4 = [{a: 1, b: 'something'}, {a: 3, b: 'something3'}]
i have mention array1, array2 , array3 inside array this:
array0 = [array1, array2, array3];
i hope can me this, thank you!
for example:
array1 = [{a: 1, b: 'something'}, {a: 2, b: 'something1'},{a: 3, b: 'something3'}]; array2 = [{a: 3, b: 'something3'}, {a: 1, b: 'something'}, {a: 4, b: 'something4'}] array3 = [{a: 3, b: 'something3'}, {a: 1, b: 'something'}, {a: 5, b: 'something5'}] = [array1, array2, array3] objects = {} counter = {} all.map(function(ary, n) { ary.map(function(obj) { var key = json.stringify(obj); objects[key] = obj; counter[key] = (counter[key] || 0) | (1 << n); }) }) intersection = [] object.keys(counter).map(function(key) { if(counter[key] == (1 << all.length) - 1) intersection.push(objects[key]); }) console.log(intersection)
the idea put objects in hash table using json representations keys.
Comments
Post a Comment