-6

I have two arrays as below:

var arr1 = [1,2,3,8,7,5,7,2,9,0];
var arr2 = [8,7,5];

I want to compare arr2 with arr1, when it will find arr2 exactly in the same sequence as it is then it should return true. i.e. if [8,7,5] is found exactly same sequence in arr1 then it will return true.

Note: We have to do this without using indexOf.

17
  • 5
    Have you tried anything so far? Do you know what a loop is and how to use it to iterate over an array? Commented Apr 25, 2017 at 15:27
  • 2
    @Dez: That doesn't take the order/sequence into account. Commented Apr 25, 2017 at 15:28
  • 3
    @Dez I don't think this is quite a duplicate, because this question asks about a subsequence, while that question asks about a subset. Commented Apr 25, 2017 at 15:28
  • 4
    Showing what you've done so far helps demonstrate how much you currently understand and don't understand, which allows you to get an answer tailored to your current level of knowledge (and prevents endless back-and-forth of "well, I don't understand that answer, can you explain this more?" and "yes, I already knew all of that, but you skipped right over X which is what I really didn't understand..." etc) Commented Apr 25, 2017 at 15:32
  • 2
    I love when people ask us to do their homework. Commented Apr 25, 2017 at 15:33

2 Answers 2

1

You could use a combination of Array#some and Array#every.

var array1 = [1, 2, 3, 8, 7, 5, 7, 2, 9, 0],
    array2 = [8, 7, 5],
    result = array1.some(function (a, i, aa) {
        return array2.every(function (b, j) {
            return aa[i + j] === b;
        });
    });
    
console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

1

You can loop through the largest array. On each iteration, compare the next values to all of the values found in the smaller array. If they all match, then it contains the smaller array.

var arr1 = [1,2,3,8,7,5,7,2,9,0];
var arr2 = [8,7,5];

console.log(doesArrayContain(arr2, arr1));

function doesArrayContain(smallestArray, biggestArray) {
    for (var i = 0; i < biggestArray.length; i++) {
    	var doesMatch = true;
        
    	for (var j = 0; j < smallestArray.length; j++) {
            if (biggestArray[i + j] !== smallestArray[j]) {
            	doesMatch = false; break;
            }
        }
        
        if (doesMatch) {
            return true;
        }
    }
    
    return false;
}

3 Comments

The OP is asking whether one array is contained in the other, not if they are the same. I.e. the result for their example would be true.
@FelixKling You're right. Updating my answer.
@FelixKling Updated :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.