Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use the next index of an array in a for..of + if condition in Javascript?

I’m creating a word filter that if index 1 = dog and index 2 = cat, it will return true. What should I put in next index for word?

let textContainer = ['bird', 'dog', 'cat', 'snake', 'rabbit', 'ox', 'sheep', 'tiger'];

for (let word of textContainer) {
  if (word === 'dog' && (next index for word) === 'cat') {
    return true;
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Use a normal for (let i = 0; i < textContainer.length; i++) so you can check i + 1

let textContainer = ['bird', 'dog', 'cat', 'snake', 'rabbit', 'ox', 'sheep', 'tiger'];

function checkTextArray() {
  for (let i = 0; i < textContainer.length; i++) {
    if (textContainer[i] === 'dog' && textContainer[i + i] === 'cat') {
        return true;
    }
  }
  return false;
}

const res = checkTextArray()
console.log(res);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading