There isn't any need to reinvent the wheel loop, at least not explicitly.

Use some as it allows the browser to stop as soon as one element is found that matches:

if (vendors.some(e => e.Name === 'Magenic')) {
  // We found at least one object that we're looking for!
}

or the equivalent (in this case) with find, which returns the found object instead of a boolean:

if (vendors.find(e => e.Name === 'Magenic')) {
  // Usually the same result as above, but find returns the element itself
}

If you'd like to get the position of that element, use findIndex:

const i = vendors.findIndex(e => e.Name === 'Magenic');
if (i > -1) {
  // We know that at least 1 object that matches has been found at the index i
}

If you need to get all of the objects that match:

if (vendors.filter(e => e.Name === 'Magenic').length > 0) {
  // The same result as above, but filter returns all objects that match
}

If you need compatibility with really old browsers that don't support arrow functions, then your best bet is:

if (vendors.filter(function(e) { return e.Name === 'Magenic'; }).length > 0) {
  // The same result as above, but filter returns all objects that match and we avoid an arrow function for compatibility
}
Answer from CAFxX on Stack Overflow
Top answer
1 of 16
2277

There isn't any need to reinvent the wheel loop, at least not explicitly.

Use some as it allows the browser to stop as soon as one element is found that matches:

if (vendors.some(e => e.Name === 'Magenic')) {
  // We found at least one object that we're looking for!
}

or the equivalent (in this case) with find, which returns the found object instead of a boolean:

if (vendors.find(e => e.Name === 'Magenic')) {
  // Usually the same result as above, but find returns the element itself
}

If you'd like to get the position of that element, use findIndex:

const i = vendors.findIndex(e => e.Name === 'Magenic');
if (i > -1) {
  // We know that at least 1 object that matches has been found at the index i
}

If you need to get all of the objects that match:

if (vendors.filter(e => e.Name === 'Magenic').length > 0) {
  // The same result as above, but filter returns all objects that match
}

If you need compatibility with really old browsers that don't support arrow functions, then your best bet is:

if (vendors.filter(function(e) { return e.Name === 'Magenic'; }).length > 0) {
  // The same result as above, but filter returns all objects that match and we avoid an arrow function for compatibility
}
2 of 16
388

2018 edit: This answer is from 2011, before browsers had widely supported array filtering methods and arrow functions. Have a look at CAFxX's answer.

There is no "magic" way to check for something in an array without a loop. Even if you use some function, the function itself will use a loop. What you can do is break out of the loop as soon as you find what you're looking for to minimize computational time.

var found = false;
for(var i = 0; i < vendors.length; i++) {
    if (vendors[i].Name == 'Magenic') {
        found = true;
        break;
    }
}
🌐
Stackoverflow
stackoverflow.design › product › develop › javascript
JavaScript - Stacks
Stacks JavaScript is currently included within various Stack Overflow projects automatically. If you’re working on a Stack Overflow project, chances are it’s already available for you!
Top answer
1 of 3
44

It's true that object lookup occurs in constant time - O(1) - so using object properties instead of an array is one option, but if you're just trying to check whether a value is included in a collection, it would be more appropriate to use a Set, which is a (generally unordered) collection of values, which can also be looked up in linear time. (Using a plain object instead would require you to have values in addition to your keys, which you don't care about - so, use a Set instead.)

const set = new Set(['foo', 'bar']);
console.log(set.has('foo'));
console.log(set.has('baz'));

This will be useful when you have to look up multiple values for the same Set. But, adding items to the Set (just like adding properties to an object) is O(N), so if you're just going to look up a single value, once, there's no benefit to this nor the object technique, and you may as well just use an array includes test.

2 of 3
15

Updated 04/29/2020

As the commenter rightly pointed out it would seem V8 was optimizing out the array includes calls. An updated version that assigns to a var and uses it produces more expected results. In that case Object address is fastest, followed by Set has and in a distant third is Array includes (on my system / browser).

All the same, I do stand by my original point, that if making micro-optimizations it is worth testing assumptions. Just make sure your tests are valid ;)

Original

Well. Despite the obvious expectation that Object address and Set has should outperform Array includes, benchmarks against Chrome indicate that implementation trumps expectation.

In the benches I ran against Chrome Array includes was far and away the best performer.

I also tested locally with Node and got more expected results. In that Object address wins, followed closely by Set has, then Array includes was marginally slower than both.

Bottom line is, if you're making micro-optimizations (not recommending that) it's worth benchmarking rather than assuming which might be best for your particular case. Ultimately it comes down to the implementation, as your question implies. So optimizing for the target platform is key.

Here's the results I got:

Node (12.6.0):

ops for Object address 7804199
ops for Array includes 5200197
ops for Set has        7178483

Chrome (75.0):
https://jsbench.me/myjyq4ixs1/1

🌐
SamanthaMing
samanthaming.com › tidbits › 81-how-to-check-if-array-includes-a-value
How to check if array includes a value in JavaScript? | SamanthaMing.com
@lolinoid: contains > @prvnbist That's a method DOM Nodes, most known example for it would be getting a list of classnames which will be a node list then you can use contain method to see if it has a classname. Or you can convert it to an array and then use includes method · You can use the in operator to loop over an object to check if a specific property key exists.
🌐
Stack Overflow
stackoverflow.com › questions › 75757391 › array-includes-with-objects-in-it-javascript
array.includes() with objects in it javascript - Stack Overflow
I have an array with objects in it, I'm trying to see if an object is included in it , but includes() returns false, even when it's true ... let borrows = [ { bookId: 0, userId: 0 }, { bookId: 4, userId: 1 }, { bookId: 1, userId: 9 }, { bookId: 2, userId: 1 }, ]; ... function returning(bookId,userId){ if(!bookId | !userId){ throw new Error('parameters not supplied') } else{ if( borrows.includes({bookId:bookId,userId:userId})){ borrows.splice({bookId:bookId,userId:userId}); } else{ throw new Error ('no such borrow exists') } } }
Find elsewhere
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › includes
Array.prototype.includes() - JavaScript | MDN
The includes() method of Array instances determines whether an array includes a certain value among its entries, returning true or false as appropriate.
🌐
Medium
bytefish.medium.com › top-5-most-popular-javascript-questions-on-stack-overflow-9077153bf1f0
Top 5 Most Popular JavaScript Questions on Stack Overflow | by Shuai Li | Medium
November 27, 2021 - Copyright: the content on Stack Overflow is distributed based on CC BY-SA. Remove a specific item from an array. Check if an element is hidden in Javascript.
🌐
Mimo
mimo.org › glossary › javascript › includes-method
JavaScript includes() method: Syntax, Usage, and Examples
Doesn't Work for Objects: For arrays of objects, includes() will not find a match unless you have the exact same object reference. Use some() for these cases instead. ... Become a full-stack developer. Learn HTML, CSS, JavaScript, and React as well as NodeJS, Express, and SQL
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-check-if-an-array-includes-an-object-in-javascript
How to check if an array includes an object in JavaScript ? | GeeksforGeeks
Check if an array includes an object in JavaScript, which refers to determining whether a specific object is present within an array.
Published   September 5, 2024
🌐
SheCodes
shecodes.io › athena › 220596-how-to-use-the-includes-method-in-javascript
[JavaScript] - How to use the .includes() method in | SheCodes
Learn how to use the `.includes()` method in JavaScript to check if a specific string or element is present in another string or array.
🌐
Sentry
sentry.io › sentry answers › javascript › how do i check if an array includes a value in javascript?
How do I check if an array includes a value in JavaScript? | Sentry
A primitive value is a value that’s not an object. There are seven primitive data types: string, number, bigint, boolean, undefined, symbol, and null. Using the includes() method is the most readable method to check if an array contains a primitive value:
🌐
Stack Abuse
stackabuse.com › javascript-check-if-array-contains-a-value-element
JavaScript: Check if Array Contains a Value/Element
March 8, 2023 - When searching for an object, includes() checks whether the provided object reference matches the one in the array.