2

I want my program to check if any two consecutive words in the array are the same. I believe that my "if" statement is correct, however the console.log shows that all consecutive words match. What am I miss here?

Any help appreciated! I'm new to this stuff :)

var wordArray = ["blue", "green", "yellow", "red", "red", "blue", "blue", "yellow"]

for (i=0; i<wordArray.length - 1; i++) {
    if (i === i+1); {
        console.log("We have a match!");
    } //Why is this loop saying that all items in the array are equal?
}

3 Answers 3

5

Try this. You were checking the index and not the element of the array, beside the wrong if statement.

for (i = 0; i < wordArray.length - 1; i++) {
    if (wordArray[i] === wordArray[i + 1]) {
        console.log("We have a match!");
    }
}

Just a hint for better length handling, if the array is only one element long:

for (i = 1; i < wordArray.length; i++) {
    if (wordArray[i - 1] === wordArray[i]) {
        console.log("We have a match!");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

try this,

var wordArray = ["blue", "green", "yellow", "red", "red", "blue", "blue", "yellow"]

for (i=1; i<wordArray.length; i++) {
    if (wordArray[i] === wordArray[i-1]) {
        console.log("We have a match!");
    }
}

4 Comments

watch the ; after if
@NinaScholz yep I missed,
@Halcyon I testing with previous word so, it should go until last.
@Azzi ok, that works. Why did you decide to flip it around?
0

It looks like you are actually comparing your index var "i" to "i + 1" in your code resulting in your console saying all items in the array are equal. Since you are actually comparing the index var , your Javascript is seeing this as :

if(1 === 2) 
    console.log("We have a match");

Since you actually want to compare the contents of wordArray :

if(wordArray[i] === wordArray[i + 1])
     console.log("We have a match!");

The important thing to remember here is that when using a "for" loop , the index variable ,"i" in this case, is only going to be an integer index for accessing the contents of the array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.