saw this as part of the interviews at facebook
Give this:
let array1 = [
{ color: 'pink', position: 'x'},
{ color: 'green', position: 'y'},
{ color: 'yellow', position: 'z'},
{ color: 'blue', position: 'w'}
]
let array2 = [
{ color: 'pink'},
{ color: 'yellow'},
{ position: 'y'}
]
filter(array1, array2) = [ { color: 'blue', position: 'w' } ]The implementation i did is kind of complicated:
function filter (arr1, arr2) {
let mapKeys = new Map();
for(let item of arr2) {
for(let key in item) {
if(!mapKeys.has(key)) {
mapKeys.set(key, [])
}
mapKeys.set(key, new Set([...mapKeys.get(key), item[key]]))
}
}
return arr1.filter((item) => {
for(let key in item) {
if(mapKeys.has(key) && mapKeys.get(key).has(item[key])) {
return false;
}
};
return true;
});
}More over, what would it be the big O of this implementation? I am still struggleing with time complexity and memory allocation
Would you have done it differently?