Help with comparing the differences between 2 arrays

sndev1099
Giga Expert

Hi, 

I need to compare 2 arrays. Find the sysids from array Array1 and see if they exist in Array2. If they don't add them to array3. The arrays are displaying correctly but when I try to log array3 to find the difference, it just seems to be logging the values in array1. Code below. Tried using the arrayUtil as well but was getting the same result

	var array1 = [];
	var array2 = [];
	var array3 = [];
	
	var legalEnt = new GlideRecord('u_department_mapping_rules');
	legalEnt.addQuery('u_department_name', current.u_department_name);
	legalEnt.query();
	
	while (legalEnt.next()) {
		array1.push(legalEnt.u_linked_legal_entity.toString());
	}
	gs.log("AB1601 array is " + array1);
	
	var compM2m = new GlideRecord('u_m2m_company_department');
	compM2m.addQuery('u_department', current.u_department_name);
	compM2m.query();
	while (compM2m.next()) {
		
		array2.push(compM2m.u_company.sys_id);
	}
	for(var i = 0; i < array1.length; i++){
		if(array2.indexOf(array1[i]) == -1) {
        array3.push(array1[i]);
		}
	}
		gs.log("AB160199 " + array3);

 

 

1 ACCEPTED SOLUTION

can you give this a go

	var array1 = [];
	var array2 = [];
	var array3 = [];
	
	var legalEnt = new GlideRecord('u_department_mapping_rules');
	legalEnt.addQuery('u_department_name', current.u_department_name);
	legalEnt.query();
	
	while (legalEnt.next()) {
		array1.push(legalEnt.u_linked_legal_entity.toString());
	}
	gs.log("AB1601 array is " + array1);
	
	var compM2m = new GlideRecord('u_m2m_company_department');
	compM2m.addQuery('u_department', current.u_department_name);
	compM2m.query();
	while (compM2m.next()) {
		
		array2.push(compM2m.u_company.sys_id +'');
	}
	for(var i = 0; i < array1.length; i++){
		if(array2.indexOf(array1[i]) == -1) {
        array3.push(array1[i] +'');
		}
	}
		gs.log("AB160199 " + array3);

View solution in original post

9 REPLIES 9

I now need to go back to the table in compM2m and remove the rows for these sysids. Do I need to another gliderecord or can I use that one?

the values pushed into array2 were not string so that was causing an issue

I now need to go back to the table in compM2m and remove the rows for these sysids. Do I need to do another gliderecord or can I reuse that so to speak?

Kieran Anson
Kilo Patron

Based on your explination, ArrayUtil's diff function should be sufficient. Have you validated your array1 and array2 have the expected results you desire

var array1 = ["123" , "234" , "345" ];
var array2 = ["12"  , "234" , "1222"];

var arrayUtil = new ArrayUtil();
var array3 = arrayUtil.diff(array1 , array2);
gs.print(array3);

Output being:

[
  "123",
  "345"
]

Yes, for those who want to manipulate / find differences / merge / etc. arrays, ArrayUtil is the best way (util 🙂) to go!