let array = [
{ en: "", ar: "", sp: "", fr: "" },
{ en: "", ar: "", sp: "", gu: "" },
{ en: "", ar: "", sp: "", hi: "" },
{ en: "", ar: "", sp: "", la: "" },
{ en: "", ar: "", sp: "" },
];
I have this array of objects and want to find the common key from all objects
the final output should be like
let array2 =[ "en", "ar", "sp"]
so the filter should only return the key's which are available in every objects. I am not able to find the best algorithm for this sorting. A little guidance will also be very helpful.
CodePudding user response:
const array = [
{ en: "", ar: "", sp: "", fr: "" },
{ en: "", ar: "", sp: "", gu: "" },
{ en: "", ar: "", sp: "", hi: "" },
{ en: "", ar: "", sp: "", la: "" },
{ en: "", ar: "", sp: "" }]
const allKeys = [...new Set(array.flatMap(i=>Object.keys(i)))]
const commonKeys = allKeys.filter(i=>!array.some(j=>!Object.keys(j).includes(i)))
console.log(commonKeys)
CodePudding user response:
let array = [
{ en: "", ar: "", sp: "", fr: "" },
{ en: "", ar: "", sp: "", gu: "" },
{ en: "", ar: "", sp: "", hi: "" },
{ en: "", ar: "", sp: "", la: "" },
{ en: "", ar: "", sp: "" },
];
let keysArr = array.map(x => Object.keys(x));
let commonKeys = keysArr.pop().reduce((res, x) => {
const isEvery = keysArr.every((i) => i.includes(x));
if (!res.includes(x) && isEvery) {
res.push(x);
}
return res;
}, []);
console.log(commonKeys);
CodePudding user response:
An approach could be like below :
Count the frequencies of keys. Sort these frequencies in descending order. And filter them having the same values as the first item.
let array = [{
en: "",
ar: "",
sp: "",
fr: ""
},
{
en: "",
ar: "",
sp: "",
gu: ""
},
{
en: "",
ar: "",
sp: "",
hi: ""
},
{
en: "",
ar: "",
sp: "",
la: ""
},
{
en: "",
ar: "",
sp: ""
},
];
const frequencies = {};
array.forEach(o => Object.keys(o).forEach(key => frequencies[key] = (frequencies[key] ?? 0) 1));
// first item has the most common key
const sorted = Object.entries(frequencies).sort(([k1, v1], [k2, v2]) => v2 - v1);
const mostCommonKeys = sorted.filter(([k, v]) => sorted[0][1] === v).map(([k, ]) => k);
console.log(mostCommonKeys)
CodePudding user response:
Pretty easy to do with reduce, Object.keys, filter, and includes.
First pass in reduce you just store the keys of the object.
Each pass after that you are just looking for the keys that exist in the current row.
let array = [
{ en: "", ar: "", sp: "", fr: "" },
{ en: "", ar: "", sp: "", gu: "" },
{ en: "", ar: "", sp: "", hi: "" },
{ en: "", ar: "", sp: "", la: "" },
{ en: "", ar: "", sp: "" },
];
const commonKeys = array.reduce((commonKeys, item, index) => {
// get the keys
const itemKeys = Object.keys(item);
// if we are at first index, return the keys
// If we are > 1, filter only the keys that are in the object
return !index ? itemKeys : commonKeys.filter(key => itemKeys.includes(key));
}, []);
console.log(commonKeys);