Function to find a value inside Array JavaScript.

This is a simple find() function to search a value inside an array, returns -1 if not found.


function find(array, value) {
if(array.indexOf) {
return array.indexOf(value);
}
for (var i = 0; ++i < array.length;) {
if(array[i]===value) {
return i;
}
}
return -1;
}
var arr = [1,2,3,4,5,6];
var check = find(arr, 5);

if(check !== -1) {
console.log('Found with the val of '+arr[check]);
} else {
console.log('Not found');
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s