Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best way to find string inside array in node.js?

I have a node.js script where I want to find if a given string is included inside an array. how can I do this?

Thanks.

like image 209
Eyal Cohen Avatar asked Jan 24 '16 12:01

Eyal Cohen


1 Answers

If I understand correctly, you're looking for a string within an array.

One simple way to do this is to use the indexOf() function, which gives you the index a string is found at, or returns -1 when it can't find the string.

Example:

var arr = ['example','foo','bar'];
var str = 'foo';
arr.indexOf(str); //returns 1, because arr[1] == 'foo'

str = 'whatever';
arr.indexOf(str); // returns -1 

Edit 19/10/2017

The introduction of ES6 gives us : arr.includes('str') //true/false

like image 197
xShirase Avatar answered Oct 05 '22 03:10

xShirase