What is the best/most efficient way to find the common/different properties of an array of objects.
I need to identify the set of properties that exists in all objects and all have the same value(the common).
Preferably I would also like to get an array with all other properties (the diff).
I have searched for an efficient library/function that can do it. But didn't find anything. So I tried on my own.
Consider this array of JS objects:
var objects = [{
id: '2j2w4f',
color: 'red',
height: 20,
width: 40,
owner: 'bob'
}, {
id: '2j2w3f',
color: 'red',
height: 20,
width: 41,
owner: 'bob'
}, {
id: '2j2w2f',
color: 'red',
height: 21,
}, {
id: '2j2w1f',
color: 'red',
height: 21,
width: 44
}];
I would like to identify color
(with value red
) as the only common property.
Note that they do not have the same set of properties. E.g. owner
is not a common property.
This is my own attempt to solve it (using lodash):
function commonDifferentProperties(objects) {
// initialize common as first object, and then remove non-common properties.
var common = objects[0];
var different = [];
var i, obj;
// iterate through the rest (note: i === 0 is not supposed to be covered by this)
for (i = objects.length - 1; i > 0; i--) {
obj = objects[i];
// compare each property of obj with current common
_.forOwn(obj, function (value, key) {
// if property not in current common it must be different
if (_.isUndefined(common[key])) {
if (!_.contains(different, key)) {
different.push(key);
}
} else if (common[key] !== value) { // remove property from common if value is not the same
delete common[key];
different.push(key);
}
});
// check that all properties of common is present in obj, if not, remove from common.
_.forOwn(common, function (value, key) {
if (_.isUndefined(obj[key])) {
delete common[key];
different.push(key);
}
});
}
return {
common: common,
different: different
};
}
jsFiddle with the example
I have also tried a mapReduce approach, but that seemed even worse.
I still think this seems a bit complex/time consuming, and I will do this on 1000-10000 objects or more with 20-50 properties each.
Any suggestions?