I have an array like
vendors = [{
Name: 'Magenic',
ID: 'ABC'
},
{
Name: 'Microsoft',
ID: 'DEF'
} // and so on...
];
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.
Unless you want to restructure it like this:
to which you can do
if(vendors.Magnetic)
You will have to loop
You have to loop, there is no way around it.
Of course you could use a library like linq.js to make this more pleasing:
(see jsFiddle for a demo)
I doubt that linq.js will be faster than a straight-forward loop, but it certainly is more flexible when things get a little more complicated.
The accepted answer still works but now we have an ECMAScript 6 native method
[Array.find][1]
to achieve the same effect.Quoting MDN:
See my jsfiddle link There is a polyfill for IE provided by mozilla
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.
I would rather go with regex.
If your code is as follows,
I would recommend
No need to reinvent the
wheelloop, at least not explicitly (using arrow functions, modern browsers only):or, better yet:
EDIT: If you need compatibility with lousy browsers then your best bet is:
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:
Array.prototype.filter()
This will return an array of all ‘Magenic’ objects, even if there is only one (will return a one-element array):
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):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.
As per ECMAScript 6 specification, you can use
findIndex
.const magenicIndex = vendors.findIndex(vendor => vendor.Name === 'Magenic');
magenicIndex
will hold either0
(which is the index in the array) or-1
if it wasn’t found.Correct me if i’m wrong..
i could have used
forEach
method like this,Nowadays i’m used to it ,because of it simplicity and self explanatory word.
Thank you.
You cannot without looking into the object really.
You probably should change your structure a little, like
Then you can just use it like a lookup-hash.
You can use lodash. If lodash library is too heavy for your application consider chunking out unnecessary function not used.
This is just one way to do this. Another one can be:
console.log(arr);
The above example can also be rewritten without using any libraries like:
Hope my answer helps.
var without2 = (arr, args) => arr.filter(v => v.id !== args.id);
Example:
without2([{id:1},{id:1},{id:2}],{id:2})
Result:
without2([{id:1},{id:1},{id:2}],{id:2})
Alternatively you can do:
Here’s the way I’d do it
array.some()
method checks if there is at least one value in an array that matches criteria and returns a boolean.From here on you can go with:
Many answers here are good and pretty easy. But if your array of object is having a fixed set of value then you can use below trick:
Map all the name in a object.
Now this dirtyObj you can use again and again without any loop.
if you’re using jquery you can take advantage of grep to create array with all matching objects:
and then use the results array:
As the OP has asked the question if the key exists or not.
A more elegant solution that will return boolean using ES6 reduce function can be
Note: The initial parameter of reduce is a
false
and if the array has the key it will return true.Hope it helps for better and cleaner code implementation
To compare one object to another, I combine a for in loop (used to loop through objects) and some().
You do not have to worry about an array going out of bounds etc, so that saves some code. Documentation on .some can be found here
An alternative way I compare one object to another is to use a nested for loop with Object.keys().length to get the amount of objects in the array. Code below:
To answer your exact question, if are just searching for a value in an object, you can use a single for in loop.
Testing for array elements:
JS Offers array functions which allow you to achieve this relatively easily. They are the following:
Array.prototype.filter
: Takes a callback function which is a test, the array is then iterated over with is callback and filtered according to this callback. A new filtered array is returned.Array.prototype.some
: Takes a callback function which is a test, the array is then iterated over with is callback and if any element passes the test, the boolean true is returned. Otherwise false is returnedThe specifics are best explained via an example:
Example:
Browser support:
These 2 function are
ES6
function, not all browsers might support them. To overcome this you can use a polyfill. Here is the polyfill forArray.prototype.some
(from MDN):You can try this its work for me.
My approach to solving this problem is to use ES6 and creating a function that does the check for us. The benefit of this function is that it can be reusable through out your project to check any array of objects given the
key
and thevalue
to check.ENOUGH TALK, LET’S SEE THE CODE
Array
Function
Call/Usage
May be too late, but javascript array has two methods
some
andevery
method that returns a boolean and can help you achieve this.I think
some
would be most appropriate for what you intend to achieve.Some validates that any of the objects in the array satisfies the given condition.
Every validates that all the objects in the array satisfies the given condition.
You can use
includes
from the Ramda library:i.e:
Source: https://ramdajs.com/docs/#includes
Try this code.
If the item or element is present then the output will show you that element. If it is not present then the output will be ‘undefined’.