How do I find the amount of values/elements that pass a test in an array?
-
If I want to find the amount of values > 0 in array for instance, how do I word it to get a return for that amount?
-
@VirtualVirgin There are several ways to do this, the most simple is to use a loop and increase a counter each time you hit a match. Or you can use one of the newer array functions such as filter (which will feature in a video next week).
const a = [1, 1, 1, 2, 3, 4, 5, 5, 5, 5, 6, 6]; // Method 1, use a loop inline function count(arr, valueToCount) { local count = 0; for (x in arr) { if (x == valueToCount) count++; } return count; } Console.print(count(a, 1)); // 3 // Method 2, use the filter function Console.print(a.filter(function(x) {return x == 1;}).length); // 3
-