How to Check If an Object Is an Array

How can I check if an object is an array?

In modern browsers you can do:

Array.isArray(obj)

(Supported by Chrome 5, Firefox 4.0, Internet Explorer 9, Opera 10.5 and Safari 5)

For backward compatibility you can add the following:

// Only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
Array.isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
};

If you use jQuery you can use jQuery.isArray(obj) or $.isArray(obj). If you use Underscore.js you can use _.isArray(obj).

If you don't need to detect arrays created in different frames you can also just use instanceof:

obj instanceof Array

How to check if variable is an object or an array?

This would help.

var a = [], b = {};

console.log(Object.prototype.toString.call(a).indexOf("Array")>-1);

console.log(Object.prototype.toString.call(b).indexOf("Object")>-1);

console.log(a.constructor.name == "Array");

console.log(b.constructor.name == "Object");

How do I check if a variable is an array in JavaScript?

There are several ways of checking if an variable is an array or not. The best solution is the one you have chosen.

variable.constructor === Array

This is the fastest method on Chrome, and most likely all other browsers. All arrays are objects, so checking the constructor property is a fast process for JavaScript engines.

If you are having issues with finding out if an objects property is an array, you must first check if the property is there.

variable.prop && variable.prop.constructor === Array

Some other ways are:

Array.isArray(variable)

Update May 23, 2019 using Chrome 75, shout out to @AnduAndrici for having me revisit this with his question
This last one is, in my opinion the ugliest, and it is one of the slowest fastest. Running about 1/5 the speed as the first example. This guy is about 2-5% slower, but it's pretty hard to tell. Solid to use! Quite impressed by the outcome. Array.prototype, is actually an array. you can read more about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

variable instanceof Array

This method runs about 1/3 the speed as the first example. Still pretty solid, looks cleaner, if you're all about pretty code and not so much on performance. Note that checking for numbers does not work as variable instanceof Number always returns false. Update: instanceof now goes 2/3 the speed!

So yet another update

Object.prototype.toString.call(variable) === '[object Array]';

This guy is the slowest for trying to check for an Array. However, this is a one stop shop for any type you're looking for. However, since you're looking for an array, just use the fastest method above.

Also, I ran some test: http://jsperf.com/instanceof-array-vs-array-isarray/35 So have some fun and check it out.

Note: @EscapeNetscape has created another test as jsperf.com is down. http://jsben.ch/#/QgYAV I wanted to make sure the original link stay for whenever jsperf comes back online.

Check if object is in array of objects

You can check if the object is present in the array using the Array.some() method (ref).

const is_present = eligiblePCVoucher.some((e) => {
return Object.entries(e).toString() === Object.entries(addressObj).toString();
});

What this will do is concatenate the key and value of each of the properties in an object and do an exact string comparison. Some() will return true only if at least an object matches

How to check if object is an array of a certain type?

Use Type.IsArray and Type.GetElementType() to check the element type of an array.

Type valueType = value.GetType();
if (valueType.IsArray && expectedType.IsAssignableFrom(valueType.GetElementType())
{
...
}

Beware the Type.IsAssignableFrom(). If you want to check the type for an exact match you should check for equality (typeA == typeB). If you want to check if a given type is the type itself or a subclass (or an interface) then you should use Type.IsAssignableFrom():

typeof(BaseClass).IsAssignableFrom(typeof(ExpectedSubclass))

How to determine if object is in array

Use something like this:

function containsObject(obj, list) {
var i;
for (i = 0; i < list.length; i++) {
if (list[i] === obj) {
return true;
}
}

return false;
}

In this case, containsObject(car4, carBrands) is true. Remove the carBrands.push(car4); call and it will return false instead. If you later expand to using objects to store these other car objects instead of using arrays, you could use something like this instead:

function containsObject(obj, list) {
var x;
for (x in list) {
if (list.hasOwnProperty(x) && list[x] === obj) {
return true;
}
}

return false;
}

This approach will work for arrays too, but when used on arrays it will be a tad slower than the first option.

How to check if property of an objects of array matches with one of the values in another array of object

First off, you'll have to make sure if the ID types are correct. Users has Number type for IDs but attendingUsers has String type.

Let's say they're both the same type for the code below (I'm going with string).

You can turn the attendingUsers array into an array of strings with:

const attendingUsersIds = attendingUsers.map(attendingUser => attendingUser.id)

Then match the ids with:

const matchedUsers = users.filter(user => attendingUsersIds.includes(user.id))

If they're intended to not be the same type, you can use user.id.toString() to turn the Number into a String or parseInt(attendingUser.id) to turn the String into a Number.

How to check if an object is not an array?

Try something like this :

obj.constructor.toString().indexOf("Array") != -1

or (even better)

obj instanceof Array

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

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

Check if object value exists within a Javascript array of objects and if not add a new object to array

I've assumed that ids are meant to be unique here. some is a great function for checking the existence of things in arrays:

const arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];

function add(arr, name) {

const { length } = arr;

const id = length + 1;

const found = arr.some(el => el.username === name);

if (!found) arr.push({ id, username: name });

return arr;

}

console.log(add(arr, 'ted'));


Related Topics



Leave a reply



Submit