HISE Logo Forum
    • Categories
    • Register
    • Login

    How do I find the amount of values/elements that pass a test in an array?

    Scheduled Pinned Locked Moved Scripting
    3 Posts 3 Posters 81 Views
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • VirtualVirginV
      VirtualVirgin
      last edited by

      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?

      You can listen to my orchestral mockups here:
      https://www.virtualvirgin.net/

      d.healeyD A 2 Replies Last reply Reply Quote 0
      • d.healeyD
        d.healey @VirtualVirgin
        last edited by d.healey

        @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
        

        Libre Wave - Freedom respecting instruments and effects
        My Patreon - HISE tutorials
        YouTube Channel - Public HISE tutorials

        1 Reply Last reply Reply Quote 0
        • A
          aaronventure @VirtualVirgin
          last edited by

          @VirtualVirgin https://forum.hise.audio//post/89104

          1 Reply Last reply Reply Quote 2
          • First post
            Last post

          25

          Online

          1.8k

          Users

          12.0k

          Topics

          104.4k

          Posts