I have the following array of strings:
JavaScript
x
2
1
array = ["fox jumps", "snail slides", "airplane flies"];
2
I’m trying to find the string in the array containing “airplane”, and return the string number in the array.
I have the following code so far:
JavaScript
1
4
1
var array = ["fox jumps", "snail slides", "airplane flies"];
2
var el = array.find(a =>a.includes("airplane"));
3
console.log(el)
4
…which finds the string “airplane flies”
From this point, how do I return the string number? in this example, it should be “3”
Advertisement
Answer
findIndex
almost does what you want, but note that arrays in JS are zero-based, and since you want a one-based result (you want to return 3
for the third element in the array, not 2
), you need to add one:
JavaScript
1
2
1
var el = array.findIndex(a =>a.includes("airplane")) + 1;
2