sfletche sfletche - 2 years ago 209
Javascript Question

Vanilla Javascript equivalent for lodash _.includes

I'm using the lodash

function 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? Is there no ES5 Array.prototype equivalent?

Or is my only option to use

Answer Source

ES7: Array.prototype.includes()

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

ES5: Array.prototype.indexOf() + ~

!!~[2, 5, 9].indexOf(5);   // true
!!~[2, 5, 9].indexOf(7);   // false

Considering how weird that looks, it's better to wrap it into a function:

function includes (array, element) { return !!~array.indexOf(element); }

and use it:

includes([2, 5, 9], 5);    // true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download