Reputation: 15
Given an array of objects. For example
let letters= [{"a":1,"b":2,"c":7}, {"d":4,"c":21,"f":2}, {"g":34,"c":2} ]
I would like to find the keys which is in all three object is common. In this case c. On output I would like to see "c". The value doesn't matter now just the key. I know how to do it with identical keys (e.g id) but no idea with different ones. Thanks for the help
Upvotes: 0
Views: 1395
Reputation: 11001
Use forEach
loop and with one iteration of keys and maintain the track
object to count the number of occurrences. After the iteration, if certain keys repeated to the count of elements mean that key exist in all.
const commonKeys = (arr) => {
const track = {};
arr.forEach((obj) =>
Object.keys(obj).forEach(
(letter) => (track[letter] = (track[letter] ?? 0) + 1)
)
);
return Object.keys(track).filter((letter) => track[letter] >= arr.length);
};
let letters = [
{ a: 1, b: 2, c: 7 },
{ d: 4, c: 21, f: 2 },
{ g: 34, c: 2 },
];
console.log(commonKeys(letters));
Upvotes: 0
Reputation: 2142
const letters = [{"a":1,"b":2,"c":7}, {"d":4,"c":21,"f":2}, {"g":34,"c":2}];
const arrayCommonElements = (arr1, arr2) => {
const counts = {};
[...arr1, ...arr2].forEach(e => counts[e] = counts[e] ? counts[e] + 1 : 1);
return Object.keys(counts).filter(e => counts[e] > 1);
}
let result = letters
.map(group => Object.keys(group))
.reduce((arr, v) => arr ? arrayCommonElements(arr,v) : v, null)
console.log(result)
Upvotes: 0
Reputation:
let letters= [{"a":1,"b":2,"c":7}, {"d":4,"c":21,"f":2}, {"g":34,"c":2}]
let result = letters
.map(group => Object.keys(group))
.reduce((arr, v) => arr ? arr.filter(key => v.includes(key)) : v, null)
console.log(result)
this will give you all common keys in an array.
Upvotes: 1
Reputation: 164766
const letters = [{"a":1,"b":2,"c":7}, {"d":4,"c":21,"f":2}, {"g":34,"c":2}]
const counts = letters.reduce((map, o) => {
Object.keys(o).forEach(key => {
map.set(key, (map.get(key) ?? 0) + 1)
})
return map
}, new Map())
const duplicates = [...counts].filter(([ _, count ]) => count === letters.length)
.map(([ key ]) => key)
console.info(duplicates)
Upvotes: 1