Reputation: 2097
I have an object containing a bunch of arrays like this:
{
names: [0, 1, 2],
gender: [2, 5, 1],
boolean: [7, 2, 1, 6]
}
How can I get the value which is present in all arrays, in this case, 1
?
Upvotes: 1
Views: 95
Reputation: 707696
I thought I'd add another solution that does not make any temporary copies of the original data which can be useful if the data is larger or memory management is important.
const data = {
names: [0, 1, 2],
gender: [2, 5, 1],
boolean: [7, 2, 1, 6]
};
function findCommon(...arrays) {
// sort arrays by length so we optimize and iterate first by the shortest array
arrays.sort((a, b) => {
return a.length - b.length;
});
let results = new Set();
// for each item in the first array
for (let item of arrays[0]) {
// look in other arrays for this value
let found = true;
for (let i = 1; i < arrays.length; i++) {
if (!arrays[i].includes(item)) {
found = false;
break;
}
}
if (found) {
results.add(item);
}
}
return results;
}
let results = findCommon(data.names, data.gender, data.boolean);
console.log(Array.from(results));
Upvotes: 1
Reputation: 2254
A way of achieving this is by getting the distinct values for all the key values and then looping through the values, checking the value exists for each key's array.
const obj = {
names: [0, 1, 2],
gender: [2, 5, 1],
boolean: [7, 2, 1, 6]
}
// [1] Get the object's keys
const keys = Object.keys(obj);
// [2] Get distinct values by combining all the key arrays.
const distinctValues = [...new Set(keys.reduce((all, curr) => {
return all.concat(obj[curr]);
}, []))];
// [3] Filter the distinct values by checking each value against
// the key's array
const presentInAll = distinctValues.filter((value) => {
return keys.every((key) => obj[key].includes(value));
});
console.log(presentInAll);
Upvotes: 3