Detecting A String In An Array In JavaScript

If you have an array of values, like this:

let arraOfValues = ['one', 'two', 'three];

Then you can use the following function to find out if a string exists in this array of values.

function containsString(needle, haystack) {
    return (haystack.indexOf(needle) > -1);
}

This uses the indexOf() method of the array object to see get the index of a item within the array. If this method returns a number greater than -1 then the index was returned and so the element exists.

Use this in the following way.

let arraOfValues = ['one', 'two', 'three];
let needle = 'one';
if (arrayContains(needle, arraOfValues) === true) {
  console.log('needle exists in array');
}

This is more or less the same as the PHP function array_search.

Add new comment

The content of this field is kept private and will not be shown publicly.