skip to Main Content

I have an array of objects:

var arr = [
0: {a: ["ram", "shyam", "kunal"], b: ["abc", "xyz", "wxd"], c: ["nyx", "lux", "poc"]},
1: {d: ["ry", "cd", "er"], e: ["ew", "op", "re", "er"], c:["er", "sd", "we"]},
2: {a: ["we", "as"], e: ["we", "lk", "pm"], c:["cv", "as", "xc"]} 
]

I am getting an array of objects and I need to find out the matched key that is common in all objects: for example here c is common in all the 3 objects. So I need c with the values in all 3. There is a high possibility that there can be more than 3 objects in an array, it can be 4 or 5. In that case how to match the key and put their values in one array?

output: key c :["nyx", "lux", "poc", "er", "sd", "we", "cv", "as", "xc"];

I am able to get a match for 2 but am facing difficulties finding when the comparison is more than 2.

js:

for (var i = 0; i < ar.length; i++) {
  for (var key in arr[0]) {
    if (i > 0) {
      if (arr[i].hasOwnProperty(key)) {
        arr[0][key].push(...arr[i][key]);
      }
    }
  }
}

This only works for 2 objects comparison.

4

Answers


  1. You can use Array.reduce for efficient grouping

    const arr = [
    {a: ["ram", "shyam", "kunal"], b: ["abc", "xyz", "wxd"], c: ["nyx", "lux", "poc"]},
    {d: ["ry", "cd", "er"], e: ["ew", "op", "re", "er"], c:["er", "sd", "we"]},
     {a: ["we", "as"], e: ["we", "lk", "pm"], c:["cv", "as", "xc"]} 
    ];
    
    const result = arr.reduce((c,data)=>{
      Object.entries(data).forEach(([k,v])=>{
        c[k] ??= [];
        c[k].push(...v)
      })
      return c;
    },{});
    
    console.log(result)
    .as-console-wrapper { max-height: 100% !important; }
    Login or Signup to reply.
  2. You can use array reduce with with a Map and at the end do map.get('c')

    var arr = [{
        a: ["ram", "shyam", "kunal"],
        b: ["abc", "xyz", "wxd"],
        c: ["nyx", "lux", "poc"]
      },
      {
        d: ["ry", "cd", "er"],
        e: ["ew", "op", "re", "er"],
        c: ["er", "sd", "we"]
      },
      {
        a: ["we", "as"],
        e: ["we", "lk", "pm"],
        c: ["cv", "as", "xc"]
      }
    ];
    
    const val = arr.reduce((acc, curr) => {
      for (let keys in curr) {
        if (!acc.has(keys)) {
          acc.set(keys, curr[keys]);
        } else {
          acc.get(keys).push(...curr[keys])
        }
      }
      return acc;
    
    }, new Map);
    console.log(val.get('c'))
    Login or Signup to reply.
  3. Here’s a function when supplied a specific key:

    const f = key => arr.reduce((l, cur) => [...l, ...(cur[key] ?? [])], [])
    

    Array#reduce is used to accumulate all values where the object contains that key, using the spread operator to combine the original array and the current array.

    If you want to have an array with all keys at once:

    arr.reduce((obj, cur) => {
      for(const i in cur)
        obj[i] = [...(obj[i] ?? []), ...cur[i]]
      return obj
    }, {})
    
    Login or Signup to reply.
  4. Please try this way.

    const arr = [
      {a: ["ram", "shyam", "kunal"], b: ["abc", "xyz", "wxd"], c: ["nyx", "lux", "poc"]},
      {d: ["ry", "cd", "er"], e: ["ew", "op", "re", "er"], c:["er", "sd", "we"]},
      {a: ["we", "as"], e: ["we", "lk", "pm"], c:["cv", "as", "xc"]} 
    ];
    
    const result = arr.reduce((res,data)=>{
      const newC = data.hasOwnProperty("c");
      if (newC)
        return [...res, ...data.c];
      return [...res];
    },[]);
    
    const newObj = {c: result}
    console.log(newObj)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search