0 votes
1 view
in Web Technology by (31.4k points)

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; i++) { 

if (a[i] === obj) { 

return true; 

   } 

 } 

return false;

}

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

1 Answer

0 votes
by (73.5k points)

To check if an array includes an object in JavaScript you can make an iteration through the array which is the best way, but the decreasing while loop is the fastest way to iterate in JavaScript. 

So you can use the following code:

function contains(a, obj) { 

var i = a.length; 

while (i--) { 

if (a[i] === obj) { 

return true; 

   } 

 } 

return false;

}

...