Sum of values in an array

Hi,

I have an array like the following
array

I am using the function to calculate the value of Download and upload in MB. The result is coming out as a single object for each occurrence. The goal is to sum all the upload values and download values

for (var i = 0; i < msg.payload.length; i++) {
  var newMsg = {};
  uploadtype = msg.payload[i][0].upload.split(' ')[1].substr(0, 2);
  if (uploadtype == "KB") {
    uploadmultiplier = ".001";
  } else if (uploadtype == "MB") {
    uploadmultiplier = "1";
  } else if (uploadtype == "GB") {
    uploadmultiplier = "1000";
  } else {
    uploadmultiplier = "0";
  }
  uploadvalue = msg.payload[i][0].upload.split(' ')[0];

  downloadtype = msg.payload[i][0].download.split(' ')[1].substr(0, 2);
  if (downloadtype == "KB") {
    downloadmultiplier = ".001";
  } else if (downloadtype == "MB") {
    downloadmultiplier = "1";
  } else if (downloadtype == "GB") {
    downloadmultiplier = "1000";
  } else {
    downloadmultiplier = "0";
  }
  downloadvalue = msg.payload[i][0].download.split(' ')[0];

  newMsg.payload = {
    //  download: msg.payload[i].PartitionKey._,
    downloadMB: downloadvalue * downloadmultiplier,
    uploadMB: uploadvalue * uploadmultiplier,
  }
  node.send(newMsg);

}

Here is the current output.

Output

Well you have only provided part of your code. Looking at it, it looks like your code is doing 'what' you told it to do, not what you 'want' it to do :joy:

You're not accumulating the running total of all the occurrences in the atrray.

Hi,

Yes, you are right the code is running correctly for what I asked it to do. I tried the SUM function to sum all the downloads but it's not working. It just gives me individual values without the sum. So I am not sure where I should add the sum code in above the working code.

You could try a function like this:

const input = msg.payload

function getSum(i){
     const tmp  = input.map(v => {
          const inputValue = v[i].split(" ")
          const sizeType = inputValue[1]
          const size = Number(inputValue[0])

          let multiplier = 0
          if (sizeType == "KB") multiplier = .001
          if (sizeType == "MB") multiplier = 1
          if (sizeType == "GB") multiplier = 1000
         
          return Number( size * multiplier )

     })
     return tmp.reduce((a, b) => a + b)
}


msg.downloadTotal = getSum("download")
msg.uploadTotal = getSum("upload")
return msg;

Which produces:

2 Likes

Hi,

My array is nested. Please see below

Every array has an object 0 hence your code is not able to fetch values.

Every array has an object 0 hence your code is not able to fetch values.

So you modified my code to make it work ?

No, I didn't. I couldn't figure it out. Apologies for being a noob.

change:

const inputValue = v[i].split(" ")

to

const inputValue = v[0][i].split(" ")
1 Like

Works. Thanks.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.