0

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

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Watch out for that time complexity
Time complexity is O(n^3)
1
  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)

Comments

0

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)

1 Comment

Reduced Time complexity to O(n^2)
0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.