JavaScript - calculate number values in a string

Paul125
Kilo Guru

Hello,

I am working on a script where I need a read an output and calculate the numbers at end of each line. I am trying the below script but I am unable make it further.

Note: script should be able to add values of 'Local Fixed disk' ONLY.

 

Output I get in the ecc queue:

Caption  Description       Size

C:       Local Fixed Disk  64422408192

D:       Local Fixed Disk  999645245440

G:       CD-ROM Disc       99884729

Script to read and calculate the size

//I pasted the above output in the Incident short descripion to make script running easier.
var gr = new GlideRecord('incident');
gr.get('number','INC7914138');
var output= gr.description;
var lines = output.split('\n');
var diskSpace = 0;
for (var i = 0; i < lines.length; i++)
	{
	var newArray = lines[i];
	
	if (newArray.indexOf('Local Fixed Disk'))
		{
		var n = newArray.split(" ");
		var disk = (n[n.length - 1]);
		diskSpace = diskSpace + parseInt(disk);
		gs.print(diskSpace);
		
	}
}

Expected output:

//addition
64422408192+999645245440 = 1064067653632

11 REPLIES 11

Thanks for the reply Cody.

Output
*** Script: NaN
*** Script: NaN
*** Script: NaN
*** Script: NaN
*** Script: NaN
*** Script: NaN
*** Script: NaN
*** Script: NaN

Paul,

 

It looks like you're passing a string into your "parseInt(disk);" 

Could you print out what you're passing as 'disk'? You will need to make sure those are numbers.

Cody - this is what I get.

*** Script: 64422408192

*** Script: 999645245440

vkachineni
Kilo Sage
Kilo Sage

//Tested on PDI

//if (newArray.indexOf('Local Fixed Disk') > -1) changed this line

 

var output= "Caption Description Size\nC: Local Fixed Disk 64422408192\nD: Local Fixed Disk 999645245440\nG: CD-ROM Disc 99884729";

var lines = output.split('\n');
var diskSpace = 0;

//gs.info("newArray toString" + lines.toString());


for (var i = 0; i < lines.length; i++)
{
var newArray = lines[i];
//gs.info("newArray =" + i + " = " + newArray);
if (newArray.indexOf('Local Fixed Disk') > -1)
{
var n = newArray.split(" ");
var disk = (n[n.length-1]);

diskSpace = diskSpace + parseInt(disk);
gs.print(diskSpace);

}
}

 

*** Script: 64422408192
*** Script: 1064067653632

 

Please mark Correct and click the Thumb up if my answer helps you resolve your issue. Thanks!
Vinod Kumar Kachineni
Community Rising Star 2022

Paul125
Kilo Guru

Thanks for the reply. Can I limit the output to below? Just additions of disks.

*** Script: 1064067653632