Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Dennis Eitner
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Dennis Eitner
Full Stack JavaScript Techdegree Graduate 25,644 Points

Find sequence in array.

How do I find if a certain sequence appears within an array? I tried indexOf and contains. But they do not work in all cases.

 var winningNumbers = [  '1,2,3',
                        '4,5,6',
                        '7,8,9',
                        '1,4,7',
                        '2,5,8',
                        '3,6,9',
                        '1,5,9',
                        '3,5,7'
                    ];

var scoreArray1 = ['1,2,3,4,5'];  //should return true
var scoreArray2 = ['1,2,3'];  //should return true
var scoreArray3 = ['1,4,5,6,7']; //should return true

1 Answer

Hi Dennis,

As your array actually comprises 8 strings each of 3 numbers, it may make life easier if you convert all 4 arrays to strings like below.

('Includes' is the modern string method which is replacing 'contains'.)

BTW - scoreArray3 should be false.

// Convert the 4 arrays to strings

var winningNumbersStr = winningNumbers.toString();
var scoreStr1 = scoreArray1.toString();
var scoreStr2 = scoreArray2.toString();
var scoreStr3 = scoreArray3.toString();

//Now perform the 3 searches

winningNumbersStr.includes(scoreStr1); // true
winningNumbersStr.includes(scoreStr2); // true
winningNumbersStr.includes(scoreStr3); // false