GergelyKarl
GergelyKarl

Reputation: 15

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 (e.g id) but no idea with different ones. Thanks for the help

Upvotes: 0

Views: 1395

Answers (4)

Siva Kondapi Venkata
Siva Kondapi Venkata

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

Ever Dev
Ever Dev

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

user12227700
user12227700

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

Phil
Phil

Reputation: 164766

  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)

Upvotes: 1

Related Questions