ServiceNow ArrayUtils API | How to find unique values in an array

As a ServiceNow developer, you’ve probably encountered a few challenges when it comes to manipulating arrays. Whether you’re trying to return unique values or search for a specific one, the process can get a bit tedious. But fear not, fellow Nerd Herders – the ArrayUtils script include has got you covered!

In this video, we’ll take a look at three methods from ArrayUtils that can save you time and lines of code. These are the type of API’s that you’ll use again and again once you know they exist. So if you’re tired of reinventing the wheel every time you work with arrays, give this video a watch and discover the power of ArrayUtils.

Here I look at 3 of those methods:

contains(Array array, Object element)

Searches the array for the specified element. Returns true if the element exists in the array, otherwise returns false.

unique(Array a)

Removes duplicate items from an array.

union(Array a, Array b)

Merge two or more arrays.

Any number of arrays can be provided as parameters.

There are more but these are the ones I tend to use most/seen the most use cases for.!/reference/api/quebec/server_legacy/r_AU-indexOf_A_N

Sample code:

var arrayUtil = new ArrayUtil(); //OR new global.ArrayUtil() if from a scoped app;

var array1 = [“INC111”, “INC222”, “INC333”, “INC444”, “INC555”];

//Contains a specified value gs.print(“Contains INC111: ” + arrayUtil.contains(a1, “INC111”));

//Gets unique gs.print(“This array has unique values: ” + arrayUtil.unique(array1));

//Combines 2 arrays and gets unique values var array2 = [“INC111”, “INC222”, “INC777”, “INC4544”, “INC554”];

gs.print(“This array is the combination of 2 arrays and makes it unique: ” + arrayUtil.union(array1, array2));


You may also like...