Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k 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 (106k 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;

}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...