I need to be able to find a common item between an arbitrary number of arrays. For example, let's say there's an object like this:
var obj = {
a: [ 15, 23, 36, 49, 104, 211 ],
b: [ 9, 12, 23 ],
c: [ 11, 17, 18, 23, 38 ],
d: [ 13, 21, 23, 27, 40, 85]
};
I'd need to determine the common item between each of these arrays. (In this case, 23).
My solution is to find the shortest array, and iterate through each item in it, checking the index of the other arrays.
var shortest = {};
var keys = [];
for ( var key in obj ) {
if ( obj.hasOwnProperty( key ) && Array.isArray( obj[ key ] ) ) {
keys.push( key );
if ( !shortest.hasOwnProperty( 'length' ) || obj[ key ].length < shortest.length ) {
shortest.name = key;
shortest.length = obj[ key ].length;
}
}
}
var res = obj[ shortest.name ].filter(function ( v ) {
for ( var i = 0; i < keys.length; i++ ) {
if ( obj[ keys[ i ] ].indexOf( v ) === -1 ) {
return false;
}
return true;
}
};
However, this seems enormously inefficient, and I'm trying to determine if there's a better way, preferably without having to loop through things multiple times.