Welcome to Community Week 2025! Join us to learn, connect, and be recognized as we celebrate the spirit of Community and the power of AI. Get the details  

sorting array

samadam
Kilo Sage

I have a script include that I ma returning array. On certain conditions I Need to combine two arrays. how can I sort it once I have the combined array? Also is there a way to remove duplicates?

 

2 REPLIES 2

debendudas
Mega Sage
Mega Sage

Hi @samadam , you can use the below script to merge and remove duplicates and sort the merged array:

// Two Arrays
var array1 = [7, 8, 1, 2, 3, 4];
var array2 = [3, 4, 5, 6];

// Merge the two arrays
var mergedArray = array1.concat(array2);

// Use ArrayUtil to remove duplicates
var arrayUtil = new ArrayUtil();
var uniqueArray = arrayUtil.unique(mergedArray);

// Sorting the Unique Array
uniqueArray.sort();

// Log the Merged Array
gs.log('Merged and deduplicated array: ' + JSON.stringify(uniqueArray));

If this solution helps you then, mark it as accepted solution ‌‌✔️ and give thumbs up 👍

Runjay Patel
Giga Sage

Hi @samadam ,

 

You can use below code to remove duplicate and short the array.

var MyScriptInclude = Class.create();
MyScriptInclude.prototype = {
    initialize: function() {},

    getSortedUniqueArray: function() {
        var array1 = ['server1', 'server3', 'server2'];
        var array2 = ['server2', 'server4', 'server1'];

        // Combine arrays
        var combinedArray = array1.concat(array2);

        // Remove duplicates (Option 1: Using Set)
        var uniqueArray = Array.from(new Set(combinedArray));

        // Sort the final array
        uniqueArray.sort();

        return uniqueArray; // Returns sorted and unique array
    },

    type: 'MyScriptInclude'
};

 

-------------------------------------------------------------------------

If you found my response helpful, please consider selecting "Accept as Solution" and marking it as "Helpful." This not only supports me but also benefits the community.


Regards
Runjay Patel - ServiceNow Solution Architect
YouTube: https://www.youtube.com/@RunjayP
LinkedIn: https://www.linkedin.com/in/runjay

-------------------------------------------------------------------------