objectduplicatesarrayobject

Remove Duplicate from Array of Object


Iam having an array of Object

       [
                {
                REQUEST_TYPE: 3,
                 E_APN: [ 'internet' ],
                 value:0
                 },
                 {  
                  REQUEST_TYPE: 3,
                  E_APN: [ 'internet' ],
                 value:0,
                 },
                  {
                  REQUEST_TYPE: 2,
                   E_APN: [ 'login' ]
                    value:0,
           
          }
    ]

if REQUEST_TYPE of each object is same, then it should merge E_APN as shown below:

 [
                {
                REQUEST_TYPE: 3,
                 E_APN: [ 'internet','internet' ],
                 value:0,
                 },
                
                  {
                  REQUEST_TYPE: 2,
                   E_APN: [ 'login' ],
                   value:0
          }
    ]

In tried using filter

const resultArr = dataArr.filter((data,index)=>{
  return dataArr.indexOf(data) === index;
})

but not able to push E_APN


Solution

  • var dup = [
       {
          REQUEST_TYPE: 3,
          E_APN: ['internet'],
          value: 0
       },
       {
          REQUEST_TYPE: 3,
          E_APN: ['internet'],
          value: 0,
       },
       {
          REQUEST_TYPE: 2,
          E_APN: ['login'],
          value: 0,
    
       }
    ]
    
    var unique = []
    var ref = {}
    var t = 0;
    for (let i = 0; i < dup.length; i++) {
       if (unique[ref[dup[i].REQUEST_TYPE]]) {
          unique[ref[dup[i].REQUEST_TYPE]].E_APN = (unique[ref[dup[i].REQUEST_TYPE]].E_APN).concat(dup[i].E_APN)
       } else {
          ref[dup[i].REQUEST_TYPE] = t++;
          unique.push(dup[i])
       }
    }
    console.log(unique)