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

Time:01-25

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;
  }
}

CodePudding user response:

You can use Array.find (or Array.some)

find returns "dog" which is not undefined (so truthy), some will return true if dog,cat is found

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

const found = textContainer
  .find((word, i, arr) => word==="dog" && arr[i 1] === "cat")
console.log(found); 
// if (found) return;

CodePudding user response:

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);

CodePudding user response:

a for of loop is not going to let you do that. You could do it with a normal for or while loop, but arrays have built in methods that can make it easy to do.

You want to use some() which will allow you to get the index and reference the array you are looping over to get the next index.

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

const result = textContainer.some((text, index, array) => text === 'dog' && array[index 1] === 'cat'); 

console.log(result);

If you want to know where in the array it is, that would be findIndex()

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

const result = textContainer.findIndex((text, index, array) => text === 'dog' && array[index 1] === 'cat'); 

console.log(result);

CodePudding user response:

You can use the indexOf method to return the index of a specific element, then use the index 1 to find the next element for the given one in the array.

The code could be like this:

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

for (let word of textContainer) {
  var index = textContainer.indexOf(word);
  if (word === "dog" && textContainer[index   1] === "cat") {
    console.log("Cat is next of Dog!");
    // return true;
    //if you're inside a function.
  }
}

Good luck!

  • Related