What is the best way to find if an object is in an array?
This is the best way I know:
function include(arr, obj) { for (var i = 0; i < arr.length; i++) { if (arr[i] == obj) return true; } } console.log(include([1, 2, 3, 4], 3)); // true console.log(include([1, 2, 3, 4], 6)); // undefined
As of ECMAScript 2016 you can use
includes()If you want to support IE or other older browsers:
EDIT: This will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it’s not present:
Mozilla’s (ECMA-262) version:
Daniel James‘s version:
roosteronacid‘s version: