Best way to play with arrays in Servicenow
Hi All,
Hope you have come across a scenario where you perform certain use cases on ARRAYS like
1. find element out of the given array
2. find the difference between two array's and what is the difference value
3. find the index of element if it exists and returns that
4. to merge two arrays without duplicates
5. remove the duplicate item and appear once
The good news is we can use the OOB function (ArrayUtil) of ServiceNow for this and get our results,
you can use this logic in the script include or any other scripting place and accomplish your task. This
array solution is helpful especially in the scenarios where you have fields of a LIST type.
So, below is the logic for all the above use-cases
1. find element out of the given array
var x = [12,13,56,15,178,23,21];
var tst = new ArrayUtil().contains(x,15);
gs.info(tst);
2. find difference between two array's and what is the difference value
var a1 = [12,13,56,15,178,23,21];
var a2 = [12,14,56,15,178,24,25];
var tst = new ArrayUtil().diff(a1,a2);
gs.info(tst);
3. find if the index of element if it exist and return that
var a1 = [12,13,56,15,178,23,21];
var tst = new ArrayUtil().indexOf(a1,15);
gs.info(tst);
4. to merge two arrays without duplicates
var a1 = [12,13,56,15,178,23,21];
var a2 = [14,15,16,17];
var tst = new ArrayUtil().union(a2,a1);
gs.info(tst);
5. remove duplicate item and appear once
var a1 = [12,13,56,15,178,23,21,13,21,65,56];
var tst = new ArrayUtil().unique(a1);
gs.info(tst);
I hope these scripts are useful to you all when working with arrays whether it is list or a field in which you
are storing multiple values and out of that you need to check something.
Mark my ARTICLE as HELPFUL and BOOKMARK it if you consider it useful.
https://www.servicenow.com/community/itsm-articles/best-way-to-play-with-arrays-in-servicenow/ta-p/2307793