Search code examples
javascriptarrayssub-array

Number of times sub-array is repeated in array - JavaScript


I have a sub-array and i am trying to find to the number of times it is repeated in the main array.

I got to the point where i can determine if it is a sub-array but cannot take it further. Any ideas how i can do that in JavaScript.

    function isSubArray(main_array, sub_array)
    {
        var i, j;
        for (i=0,j=0; i<main_array.length && j<sub_array.length;) 
        {
           if (main_array[i] !== sub_array[j]) 
           {
              ++i;
           }
           else if (main_array[i] === sub_array[j])
           {
              ++i; ++j;
           }
        }
        if(j == sub_array.length)
        {
           return true;
        }
        else
        {
           return false;
         }
     }

Example:

array = 1,2,3,4,5,1,2,3 sub_array = 1,2,3

The sub_array repeats in the main array 2 times


Solution

  • Here is a dynamic function made by me to get your required solution,

    I have taken two different arrays and returned the repeated count of both dynamic.

    var array = [1,2,3,4,5,1,2,3];
    var array1 = [1,2,3,4,5,1,2,3,5,9,1,2,3];
    var sub_array = [1,2,3];
    
    function getRepeatedCount(array,sub_array)
    {
        var count = 0;
        for(i = 0; i < array.length; i++  )
        {
            // console.log((array.slice(i,i + sub_array.length)) === sub_array)
            var repeated = ((array.slice(i,i + sub_array.length)).length==sub_array.length && (array.slice(i,i + sub_array.length)).every(function(v,i) { return v === sub_array[i]}))
            if(repeated)
            {
                count += 1;
            }
        }
        return count;
    }
    console.log("Array1",array, "Sub Array", sub_array, "Repeated count -> ",getRepeatedCount(array,sub_array));
    console.log("Array1",array1, "Sub Array", sub_array, "Repeated count -> ",getRepeatedCount(array1,sub_array));

    PLEASE RUN THE ABOVE SNIPPET

    Procedure:

    I created a function, which slices the main array into chunks(parts) that equals the length of the subarray and compare each chunk of small array with the subarray.

    If the chunk(part) equals the sub_array, then a count variable is incremented in the function and gets returned.

    HERE IS A WORKING DEMO

    Thus, I made the function dynamic so that you can call it as many times you want with different arrays and sub_arrays.