When reading your solution, i see there are 3 parts.
Part 1: if array 2 is smaller than array 1, then array 2 can not be a sub array of array 1
Part 2: compare each element of 2 array when they have the same size. Array 2 is sub array of Array 1 if all elements are the same
Part 3: compare each element of 2 array when array 2 size is smaller than array 1 size. There is an issue in part 2 and part 3. They have the same logic. Part 3 works fine if 2 array have the same size. In fact, if two arrays have the same size, part 2 would have taken care of this scenario. So step 2 and 3 are basically the same thing
I would revise part 3 as follow:
Part 3 (new): if array 2 is smaller than array 1, and array 2 is contained within array 1, then array 1 should have a sub array, in which each element of that sub array is equaled to each element in array 2
step 1: compare each element of array 2 to the sub array of array 1.
step 2: if all elements are equals, then array 2 is contained in array 1. if any of elements are not equal, repeat step 1 for the next sub array of array 1.
Note: if you are familiar with recursion, the solution will be neater. Every time we repeat step 1, we are solving the same problem as part of the general solution.
Below is the recursive solution. This solution does not take into account null and empty array.
<!DOCTYPE html> <html> <body> <p>This example calls a function which performs a calculation, and returns the result:</p> <p id="demo"></p> <script> function findSubArray(bigArray, smallArray, startIndexOfSubArray) { if((bigArray.length - startIndexOfSubArray) < smallArray.length) return false; for(index = 0; index < smallArray.length; index++) { if(bigArray[startIndexOfSubArray + index] != smallArray[index]){ return findSubArray(bigArray, smallArray, startIndexOfSubArray = startIndexOfSubArray + 1); } } return true; } var bigArray = [1,3,3,4,5,6]; var smallArray = [4,5,7]; var isSubArray = findSubArray(bigArray, smallArray, 0); document.getElementById("demo").innerHTML = isSubArray.toString(); </script> </body> </html>
==, usearr1[i].equals(arr2[i])arr1[i]witharr2[y], notarr2[i]. Also, makeigo up toarr1.length, notarr2.length.