How do I check if an array includes an object in JavaScript? -


what concise , efficient way find out if javascript array contains object?

this way know it:

function contains(a, obj) {     (var = 0; < a.length; i++) {         if (a[i] === obj) {             return true;         }     }     return false; } 

is there better , more concise way accomplish this?

this closely related stack overflow question best way find item in javascript array? addresses finding objects in array using indexof.

current browsers have array#includes, exactly that, is supported, , has polyfill older browsers.

you can use array#indexof, less direct, doesn't require polyfills out of date browsers.

jquery offers $.inarray, functionally equivalent array#indexof.

underscore.js, javascript utility library, offers _.contains(list, value), alias _.include(list, value), both of use indexof internally if passed javascript array.

some other frameworks offer similar methods:

notice frameworks implement function, while others add function array prototype.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -