Json array remove duplicates based on key and value

Jennnie
Tera Contributor

Hello,

 

I called glideRecord and push the result value into the array, which has key and value 

like, ({"sys_id" : 1 , "name" : whatever.user.name  +  "/ "+  whatever.user.title)

The problem is, there are duplicate results with different sys_id, but same name.

so i want to remove the duplicate value with same name.

 

i tried ArrayUtil().unique() but this not worked.

 

Anyone can help? 

 

Thanks in  advance

 

4 REPLIES 4

Anil Lande
Kilo Patron

Hi,

Can you please share your script part?

It would be easy to modify your script and suggest an approach.

 

Thanks,
Anil Lande

Please appreciate the efforts of community contributors by marking appropriate response as correct answer and helpful, this may help other community users to follow correct solution in future.
Thanks
Anil Lande

Arav
Tera Guru
Tera Guru

Hi Jennie,

What is the business requirement here ? If you remove duplicates with same name, won't you be missing the corresponding sys ids ?

If sys id is not of significance, why don't you form an array of names (i.e. name + title combo) and then remove dupes using Array Util's unique method ? 

Thanks,

Arav

Valmik Patil1
Kilo Sage

Hi,

You can refer below script.

try running in background by passing your sample JSON array

var arrayWithDuplicates = [
    {"type":"LICENSE", "licenseNum": "12345", state:"NV"},
    {"type":"Name", "licenseNum": "A7846", state:"CA"},
    {"type":"LICENSE", "licenseNum": "12345", state:"OR"},
    {"type":"LICENSE1", "licenseNum": "10849", state:"CA"},
    {"type":"LICENSE", "licenseNum": "B7037", state:"WA"},
    {"type":"LICENSE", "licenseNum": "12345", state:"NM"}
];

function removeDuplicates(originalArray, prop) {
     var newArray = [];
     var lookupObject  = {};

     for(var i in originalArray) {
        lookupObject[originalArray[i][prop]] = originalArray[i];
     }

     for(i in lookupObject) {
         newArray.push(lookupObject[i]);
     }
      return newArray;
 }
// please pass your JSON array to this funtion as first parameter
var uniqueArray = removeDuplicates(arrayWithDuplicates, "type");    // here instead of "type" give your key name which you want to be unique
gs.log("uniqueArray is: " + JSON.stringify(uniqueArray));

Let me know if you need any other help

Thanks,

Valmik

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

what's your business requirement around pushing it into json?

Regards
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader