简体   繁体   中英

Find duplicates in "Array of objects" with different keys in javascript

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

  1. Iterate the array of objects and build up a map of key counts
  2. Filter that map down to counts equal to the number of elements in the array
  3. Return the keys

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM