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 (eg id) but no idea with different ones. Thanks for the help
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)
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.
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)
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.