How to determine if Javascript array contains an object with an attribute that equals a given value?

How to determine if Javascript array contains an object with an attribute that equals a given value?

I have an array like
vendors = [
{
Name: ‘Magenic’,
ID: ‘ABC’
},
{
Name: ‘Microsoft’,
ID: ‘DEF’
} //and so on goes array…
];

How do I check this array to see if Magenic exists? I don’t want to loop, unless I have to. I’m working with potentially a couple thousand records.
UPDATED
Since this has been a popular post, I thought I’d share something new I found. And it appears @CAFxX has already shared this! I should read these more often. I came across https://benfrain.com/understanding-native-javascript-array-methods/.
vendors.filter(function(vendor){ return vendor.Name === “Magenic” });

And with ECMAScript 2015 it is even simpler using the new arrow functions:
vendors.filter(vendor => (vendor.Name === “Magenic”));

Solutions/Answers:

Solution 1:

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;
    }
}

Solution 2:

No need to reinvent the wheel loop, at least not explicitly (using arrow functions, modern browsers only):

if (vendors.filter(e => e.Name === 'Magenic').length > 0) {
  /* vendors contains the element we're looking for */
}

or, better yet:

if (vendors.some(e => e.Name === 'Magenic')) {
  /* vendors contains the element we're looking for */
}

EDIT: If you need compatibility with lousy browsers then your best bet is:

if (vendors.filter(function(e) { return e.Name === 'Magenic'; }).length > 0) {
  /* vendors contains the element we're looking for */
}

Solution 3:

No loop necessary. Three methods that come to mind:

Array.prototype.some()

This is the most exact answer for your question, i.e. “check if something exists”, implying a bool result. This will be true if there are any ‘Magenic’ objects, false otherwise:

let hasMagenicVendor = vendors.some( vendor => vendor['Name'] === 'Magenic' )

Array.prototype.filter()

This will return an array of all ‘Magenic’ objects, even if there is only one (will return a one-element array):

let magenicVendors = vendors.filter( vendor => vendor['Name'] === 'Magenic' )

If you try to coerce this to a boolean, it will not work, as an empty array (no ‘Magenic’ objects) is still truthy. So just use magenicVendors.length in your conditional.

Array.prototype.find()

This will return the first ‘Magenic’ object (or undefined if there aren’t any):

let magenicVendor = vendors.find( vendor => vendor['Name'] === 'Magenic' );

This coerces to a boolean okay (any object is truthy, undefined is falsy).


Note: I’m using vendor[“Name”] instead of vendor.Name because of the weird casing of the property names.

Note 2: No reason to use loose equality (==) instead of strict equality (===) when checking the name.

Solution 4:

The accepted answer still works but now we have an ECMAScript 6 native method [Array.find][1] to achieve the same effect.

Quoting MDN:

The find() method returns the value of the first element in the array
that satisfies the provided testing function. Otherwise undefined is
returned.

var arr = []; 
var item = {
  id: '21',
  step: 'step2',
  label: 'Banana',
  price: '19$'
};

arr.push(item);
/* note : data is the actual object that matched search criteria 
  or undefined if nothing matched */
var data = arr.find( function( ele ) { 
    return ele.id === '21';
} );

if( data ) {
 console.log( 'found' );
 console.log(data); // This is entire object i.e. `item` not boolean
}

See my jsfiddle link There is a polyfill for IE provided by mozilla

Solution 5:

Unless you want to restructure it like this:

vendors = {
    Magenic: {
      Name: 'Magenic',
      ID: 'ABC'
     },
    Microsoft: {
      Name: 'Microsoft',
      ID: 'DEF'
    } and so on... 
};

to which you can do if(vendors.Magnetic)

You will have to loop

Solution 6:

As per ECMAScript 6 specification, you can use findIndex.

const magenicIndex = vendors.findIndex(vendor => vendor.Name === 'Magenic');

magenicIndex will hold either 0 (which is the index in the array) or -1 if it wasn’t found.