ServiceNow Scripting Question – Array
Array A = [1,2,3,4,5], Print in reverse order.
Method 1:
var numbers_array = [1, 2, 3, 4, 5]; gs.info("Original Array: "+numbers_array); numbers_array.reverse(); gs.info("Reversed Array: "+numbers_array);
Method 2:
var original_array = [1, 2, 3, 4]; var reversed_array = []; gs.info("Original Array: "+original_array); for (var i = original_array.length - 1; i >= 0; i--) { reversed_array.push(original_array[i]); } gs.info("Reversed Array: "+reversed_array);
Array A = [1,3,5,7] & B = [2,3,4,5,6,9]. Intersection of two Arrays.
var first_array = [1, 3, 5, 7]; var second_array = [2, 3, 4, 5, 6, 9]; var new_array = []; for (var i = 0; i < first_array.length; i++) { for (var j = 0; j < second_array.length; j++) { if (first_array[i] === second_array[j]) { new_array.push(first_array[i]); } } } gs.info("Array obtained is : "+new_array);
Array A = [1,3,5,7] & B = [2,3,4,5,6,9]. Union of two Arrays.
var first_array = [1, 3, 5, 7]; var second_array = [2, 3, 4, 5, 6, 9]; var new_array = first_array.concat(second_array) gs.info("Array is : "+new_array);
Array A= [1,3,5,7,2,3,4,5,6,9], Remove duplicates.
var new_array= [1,3,5,7,2,3,4,5,6,9] function removeDuplicates(arr) { var unique = []; for (var i = 0; i < arr.length; i++) { if (unique.indexOf(arr[i]) === -1) { unique.push(arr[i]); } } return unique; } gs.info("Unique Array "+removeDuplicates(new_array));
Array A = [1,3,5,7,2,3,4,5,6,9], Sorting an Array.
var new_array= [1,3,5,7,2,3,4,5,6,9]; gs.info("Array obtained is : "+new_array.sort());
Array A = [1,2,3] & B = [3,4,5]. Find out two elements which product is 6.
var array_first = [1,2,3]; var array_second = [3,4,5]; var product = 6; for(var i=0; i<array_first.length;i++){ for(var k=0; k<array_second.length; k++){ if(array_first[i]*array_second[k] == product){ gs.info('Position: '+i+'--'+k+' Element '+array_first[i]+'--'+array_second[k]); break; } } }
No responses yet