Skip to main content
Best answer

How to count values in Code step?

  • January 29, 2022
  • 4 replies
  • 257 views

michael291
Forum|alt.badge.img+4

Hello,

 

I am trying to count the quantity of several products in a line item order (WooCommerce). I.e. the line items in the order look like: 

Product 1 × 3, Product 2 × 1, Product 3 × 2

 

So: 
Product 1 was ordered 3 times
Product 2 was ordered once
Product 3 was ordered 2 times

And the result/output should be: 
6

 

I am trying to count all quantities together. I already tried to solve this with the Formatter, but didn’t have success. Is it possible to do this with JavaScript or Phyton? Or is there another way?

 

Thanks a lot for your support, 
M.

Best answer by Troy TessaloneBest answer by Troy Tessalone

@michael291 

This can be done in a Code step: https://zapier.com/apps/code/help

 

Try this JavaScript…

CONFIG

 

CODE

let Count = 0;
let Items = inputData.Items.split(",");
for (let i = 0; i < Items.length ; i++) {
  Items[i] = Items[i].split(";")[1].trim();
  Count += parseInt(Items[i]);
}

output = [{Count, Items}];

 

RESULTS

 

View original
Did this topic help you find an answer to your question?
This post has been closed for comments. Please create a new post if you need help or have a question about this topic.

4 replies

Troy Tessalone
Forum|alt.badge.img+14

Hi @michael291 

Can you post screenshots with how the actual data comes thru on the Zap step that you are trying to use?


michael291
Forum|alt.badge.img+4
  • Author
  • Builder
  • 74 replies
  • January 29, 2022

Hi @Troy Tessalone 

thanks for help. Here’s the screenshot where I “fetch” the data from the line items order. 

Hope that will help you. 

 

M.

 

 


Troy Tessalone
Forum|alt.badge.img+14
  • Zapier Expert
  • 30995 replies
  • Answer
  • January 29, 2022

@michael291 

This can be done in a Code step: https://zapier.com/apps/code/help

 

Try this JavaScript…

CONFIG

 

CODE

let Count = 0;
let Items = inputData.Items.split(",");
for (let i = 0; i < Items.length ; i++) {
  Items[i] = Items[i].split(";")[1].trim();
  Count += parseInt(Items[i]);
}

output = [{Count, Items}];

 

RESULTS

 


michael291
Forum|alt.badge.img+4
  • Author
  • Builder
  • 74 replies
  • January 29, 2022

@Troy Tessalone Wow, that’s amazing. Works perfectly!!! Thank you so much for your help.