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

What is the most concise and efficient way to find out if a JavaScript array contains an object?

This is the only way I know to do it:

function contains(a, obj) 

  for (var i = 0;
 i < a.length;

  if (a[i] === obj) 

  return true;

  return false;

Is there a better and more concise way to accomplish this?

This is very closely related to Stack Overflow question Best way to find an item in a JavaScript Array? which addresses finding objects in an array using indexOf.

Text Copied From
on : Sat, Oct 25, 2008 Views : 2044654

Accepted Answer

Current browsers have Array#includes, which does exactly that, is widely supported, and has a polyfill for older browsers.

You can also use Array#indexOf, which is less direct, but doesn't require Polyfills for out of date browsers.

jQuery offers $.inArray, which is functionally equivalent to Array#indexOf.

underscore.js, a JavaScript utility library, offers _.contains(list, value), alias _.include(list, value), both of which use indexOf internally if passed a JavaScript array.

Some other frameworks offer similar methods:

Notice that some frameworks implement this as a function, while others add the function to the array prototype.

Text Copied From
on : Thu, Sep 24, 2009

Ask Question

If you want to ask question you must LogIn or SignUp
Login SignUp

Quick Links



Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..


Login to Open ESchool OR Create your account    Login   SignUp