简体   繁体   中英

Finding occurrence of first string in an array in js

Suppose I am given an array

myArray=[10,true,1.5,'Asia', 20, 'rat'];

Now which function should I use to get the index of the first occurrence of a string in array?

You can use findIndex()

 const result = [10,true,1.5,'Asia', 20, 'rat'].findIndex(item => typeof item === "string"); console.log(result);

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function.

Source: MDN Web Docs

If you want to find the first index of the string then findIndex would be one of the best options.

 const myArray = [10, true, 1.5, "Asia", 20, "rat"]; const index = myArray.findIndex((s) => typeof s === "string"); console.log(index);

Use findIndex

 const myArray=[10,true,1.5,'Asia', 20, 'rat']; const index = myArray.findIndex( ( el ) => { return typeof el === 'string'; } ); console.log('Answer: ', index);

Normally you can use findIndex, but you can also use normal for.. loop and break

 let myArray = [10, true, 1.5, 'Asia', 20, 'rat']; let ind = -1; for (let x = 0; x < myArray.length; x++) { if (typeof myArray[x] === 'string') { ind = x; break; } } console.log(ind)

For completeness, here's the Mozilla's specification of the Array.prototype.filter() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM