Vanilla Javascript equivalent for lodash _.includes

I am using lodash function includes

to check if a target value exists in an array ...

_.includes(array, target) 

      

and was hoping to find a good equivalent in ES5 (or ES6)

Did I miss something? Isn't there an ES5 equivalent Array.prototype?

Or is my only option to use indexOf

?

+3


source to share


1 answer


ES7: Array.prototype.includes()

[1, 2, 3].includes(2);     // true

      

ES5: Array.prototype.indexOf()

>= 0

[2, 5, 9].indexOf(5) >= 0;   // true
[2, 5, 9].indexOf(7) >= 0;   // false

      



If you prefer a function:

function includes (array, element) { return array.indexOf(element) >= 0 }

      

and use it like:

includes([2, 5, 9], 5);    // true

      

+4


source







All Articles