How to get the count of an array of items

  • 2 December 2021
  • 6 replies
  • 1148 views
How to get the count of an array of items
Userlevel 7
Badge +14

📌  We do our best to ensure that the code in these articles works as advertised, but please be aware that Zapier Support does not officially help with code steps due to their advanced nature. Feel free to comment on the article or ask in the Zapier Community, where we have code-savvy folks (including the author of this post).

If you’ve ever needed to count the number of items in an array and weren’t quite sure how to do it, the solution lies with Code by Zapier. And it’s easy to do!

The Setup

 

COPY THE CODE

let Set = inputData.Set;
let SetCount = 0; // defaults the Set Count to 0

// If Set exists
if (Set) {
Set = Set.split(","); // creates array by splitting Input Data Variable at commas
SetCount = Set.length; // determines the length of the array (aka number of array items)
}

output = [{SetCount, Set}];

 

The Results

 

Contribution by Troy Tessalone

Troy is a Certified Zapier Expert who automates workflows with no-code and low-code apps to help clients save time and make money.


6 replies

Userlevel 7
Badge +11

Dude! I just used this 🙂 The API I’m getting data from has a field that shows everyone who liked something, but doesn’t provide the number. I used this code and it worked like a charm!

Userlevel 7
Badge +14

@nicksimard 

Glad you found some value in this!

Userlevel 7
Badge +14

@align432YOGA 

Check out the updated JS Code above.

@Troy Tessalone, I’m using this exact code. 
 

It seems like my test worked because because I provided values. 
 

But when my student triggered the Zap, they didn’t have any values to split. Thus the error. 
 

This Zap is triggered when a student sends in homework. So every student at some point will have no values/string to split. 
 

How do I factor this into the code above? 

Userlevel 7
Badge +14

@align432YOGA 

The code above was updated.

 

Thanks @Troy Tessalone. I’ve copied it and it works!

Reply