Remove matching entries from an array

Rakshanda Kunte
Tera Contributor

Hi All,

 

Requirement:

I have 2 arrays.

array1 = ['Software', 'Hardware', 'Service Catalog']

array2 = ['Technology', 'Governance', 'Hardware', 'HR', 'Service Desk', 'Service Catalog', 'Software']

 

If whatever present in array1, is matching the names in array 2, then remove those names from array 2 and give the new array.

 

Output should be:

array2 = ['Technology', 'Governance', 'HR', 'Service Desk']

 

Kindly, help with scripting.

6 REPLIES 6

Harsh_Deep
Giga Sage
Giga Sage

Hello @Rakshanda Kunte 

Please use below code -

 

var array1 = ['Software', 'Hardware', 'Service Catalog'];
var array2 = ['Technology', 'Governance', 'Hardware', 'HR', 'Service Desk', 'Service Catalog', 'Software'];

var newArray2 = [];
for (var i = 0; i < array2.length; i++) {
    var element = array2[i];
    if (array1.indexOf(element) === -1) {
        newArray2.push(element);
    }
}
array2 = newArray2;
gs.info(array2);

 

Or

var arrayUtil = new ArrayUtil();
var array1 = ['Software', 'Hardware', 'Service Catalog'];
var array2 = ['Technology', 'Governance', 'Hardware', 'HR', 'Service Desk', 'Service Catalog', 'Software'];
var newArray2 = [];
array2 = newArray2;
var n = arrayUtil.diff(array1, array2);
gs.info(n);
 

Mark Correct if this solves your issue and also mark 👍 Helpful if you find my response worthy based on the impact.

Thanks @Maik Skoddow.

 

Can you also pleas help on 'how to get count of how many groups we have in an array'?

 

Hello @Rakshanda Kunte 

 

Use this for count-

var arrayUtil = new ArrayUtil();
var array1 = ['Software', 'Hardware', 'Service Catalog'];
var array2 = ['Technology', 'Governance', 'Hardware', 'HR', 'Service Desk', 'Service Catalog', 'Software'];
var newArray2 = [];
array2 = newArray2;
var n = arrayUtil.diff(array1, array2);
var count = n.length;
gs.info(count);

 

Mark Correct if this solves your issue and also mark 👍 Helpful if you find my response worthy based on the impact.

Hi @Rakshanda Kunte ,

 

You can use the ArrayUtil - Global API to achieve your requirement.

var array1 = ['Software', 'Hardware', 'Service Catalog'];
var array2 = ['Technology', 'Governance', 'Hardware', 'HR', 'Service Desk', 'Service Catalog', 'Software'];

var output = new ArrayUtil().diff(array2, array1);
gs.info(output );

 

In order to count the elemnts in each array you can use the below:

var array1 = ['Software', 'Hardware', 'Service Catalog'];
var array2 = ['Technology', 'Governance', 'Hardware', 'HR', 'Service Desk', 'Service Catalog', 'Software'];

var result = new ArrayUtil().diff(array2, array1);
gs.info(array1.length);
gs.info(array2 .length);
gs.info(result .length);

 

Please mark this as correct answer and helpful if it resolved, or mark this helpful if this help you to reach towards solution.

----------------------------------------------------------------
Mark this as Helpful / Accept the Solution if this helps.