bilbo
bilbo

Reputation: 11

Filter duplicates and group them into separated arrays

I need to get objects with exact same key1 and key2 (duplicates). Difference between objects key3 must be less than 1 to pass those objects as duplicates. Those object must become grouped into separated arrays. Objects, which are not duplicates are irrelevant and won't appear in output.

input

[
    {
        key1: 'A',
        key2: 'B',
        key3: 5
    },
    {
        key1: 'C',
        key2: 'V',
        key3: 7
    },
    {
        key1: 'C',
        key2: 'V',
        key3: 6
    },
    {
        key1: 'A',
        key2: 'B',
        key3: 3
    },
    {
        key1: 'A',
        key2: 'B',
        key3: 5
    },
    {
        key1: 'L',
        key2: 'V',
        key3: 1
    },
    {
        key1: 'A',
        key2: 'B',
        key3: 6
    },
    {
        key1: 'A',
        key2: 'B',
        key3: 7
    }
]

output

[
    [
        {
            key1: 'A',
            key2: 'B',
            key3: 5
        },
        {
            key1: 'A',
            key2: 'B',
            key3: 5
        },
        {
            key1: 'A',
            key2: 'B',
            key3: 6
        },
        {
            key1: 'A',
            key2: 'B',
            key3: 7
        }
    ],
    [
        {
            key1: 'C',
            key2: 'V',
            key3: 6
        },
        {
            key1: 'C',
            key2: 'V',
            key3: 7
        }
    ]
]

I got to the moment where I have a big list of duplicates, but I have problem to get them grouped

Upvotes: 1

Views: 58

Answers (1)

Majed Badawi
Majed Badawi

Reputation: 28414

You use a set to store the objects with the same key1 and key2 and then get the ones with more than one occurrence:

let set = {};
let list = [
     {
          key1: 'A',
          key2: 'B',
          key3: 5
     },
     {
          key1: 'C',
          key2: 'V',
          key3: 7
      },
      {
          key1: 'C',
          key2: 'V',
          key3: 1
      },
      {
          key1: 'A',
          key2: 'B',
          key3: 3
      },
      {
          key1: 'A',
          key2: 'B',
          key3: 5
      },
      {
          key1: 'L',
          key2: 'V',
          key3: 1
      }
];
for(let i = 0; i < list.length; i++){
     let obj = list[i];
     let k1 = obj['key1'], k2 = obj['key2'];
     if(!set[k1+k2])
          set[k1+k2] = [obj];
     else
          set[k1+k2].push(obj);
}
let res = [];
for (var key in set) {
     if (set.hasOwnProperty(key) && set[key].length > 1) {
          res.push(set[key])
     }
}
console.log(res);

Upvotes: 1

Related Questions