Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to compare two arrays and get unique values

Hari1
Mega Sage

Hi,

I have 2 arrays. I need to get the users not present in the other array. I am using the below code I am able to get unique users but there are duplicates in it.

var arrCapUsers = ["a","b","c","d","e"];
var arrGrpUsers = ["a","b","c","d","e","f","g","h","i","j","k","l"];
var arrFinal = [];


for(var i=0; i<arrCapUsers.length; i++){
  for(var j=0; j<arrGrpUsers.length; j++){
    if(arrCapUsers[i] != arrGrpUsers[j]){
    arrFinal.push(arrGrpUsers[i])
  	}
  }
}

gs.info("arrFinal:"+arrFinal);


1 ACCEPTED SOLUTION

Hi,

then do this ->use diff() method

var arrCapUsers = ["a","b","c","d","e"];
var arrGrpUsers = ["a","b","c","d","e","f","g","h","i","j","k","l"];
var arrFinal = [];

var arrayUtil = new global.ArrayUtil();

arrFinal = arrayUtil.diff(arrGrpUsers,arrCapUsers);

gs.info(arrFinal);

Output:

find_real_file.png

Regards
Ankur

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

View solution in original post

5 REPLIES 5

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

what do you mean by Unique?

you can use ArrayUtil class and it has different functions

ArrayUtil - Global

Regards
Ankur

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

I want the output to be as ["f","g","h","i","j","k","l"] discard ["a","b","c","d","e"] as it is present in both the arrays.

Hi,

then do this ->use diff() method

var arrCapUsers = ["a","b","c","d","e"];
var arrGrpUsers = ["a","b","c","d","e","f","g","h","i","j","k","l"];
var arrFinal = [];

var arrayUtil = new global.ArrayUtil();

arrFinal = arrayUtil.diff(arrGrpUsers,arrCapUsers);

gs.info(arrFinal);

Output:

find_real_file.png

Regards
Ankur

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

Maik Skoddow
Tera Patron
Tera Patron

Hi Hari

on page https://community.servicenow.com/community?id=community_article&sys_id=d5d43229db47d0943daa1ea668961... all required methods of the ArrayUtil class are introduced.

To my mind, you can use diff() and unique() without implementing anything.

Kind regards
Maik