Checking if an object is array-like
As best I've found in my research on this topic, you have only a couple choices:
You can look only at the
.length
property and accept any object that seems to have an appropriate.length
property that isn't any other things you know you should eliminate (like a function).You can check for specific array-like objects (
HTMLCollection
,nodeList
) and bias in favor of them.
Here are two options for the first method - one that doesn't accept a zero length and one that does (these incorporate suggestions by gilly3 and things we see in jQuery's similar function):
// see if it looks and smells like an iterable object, but don't accept length === 0
function isArrayLike(item) {
return (
Array.isArray(item) ||
(!!item &&
typeof item === "object" &&
item.hasOwnProperty("length") &&
typeof item.length === "number" &&
item.length > 0 &&
(item.length - 1) in item
)
);
}
This, of course, reports false
for items with .length === 0
, If you want to allow .length === 0
, then the logic can be made to include that case too.
// see if it looks and smells like an iterable object, and do accept length === 0
function isArrayLike(item) {
return (
Array.isArray(item) ||
(!!item &&
typeof item === "object" &&
typeof (item.length) === "number" &&
(item.length === 0 ||
(item.length > 0 &&
(item.length - 1) in item)
)
)
);
}
Some test cases: http://jsfiddle.net/jfriend00/3brjc/
2) After checking to see that it's not an actual array, you can code to check for specific kinds of array-like objects (e.g. nodeList
, HTMLCollection
).
For example, here's a method I use when I want to make sure I include nodeList and HTMLCollection array-like objects:
// assumes Array.isArray or a polyfill is available
function canAccessAsArray(item) {
if (Array.isArray(item)) {
return true;
}
// modern browser such as IE9 / firefox / chrome etc.
var result = Object.prototype.toString.call(item);
if (result === "[object HTMLCollection]" || result === "[object NodeList]") {
return true;
}
//ie 6/7/8
if (typeof item !== "object" || !item.hasOwnProperty("length") || item.length < 0) {
return false;
}
// a false positive on an empty pseudo-array is OK because there won't be anything
// to iterate so we allow anything with .length === 0 to pass the test
if (item.length === 0) {
return true;
} else if (item[0] && item[0].nodeType) {
return true;
}
return false;
}
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.
How to check if variable is array?... or something array-like
If you are using foreach
inside a function and you are expecting an array or a Traversable object you can type hint that function with:
function myFunction(array $a)
function myFunction(Traversable)
If you are not using foreach
inside a function or you are expecting both you can simply use this construct to check if you can iterate over the variable:
if (is_array($a) or ($a instanceof Traversable))
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 to detect if a variable is an array
Type checking of objects in JS is done via instanceof
, ie
obj instanceof Array
This won't work if the object is passed across frame boundaries as each frame has its own Array
object. You can work around this by checking the internal [[Class]] property of the object. To get it, use Object.prototype.toString()
(this is guaranteed to work by ECMA-262):
Object.prototype.toString.call(obj) === '[object Array]'
Both methods will only work for actual arrays and not array-like objects like the arguments
object or node lists. As all array-like objects must have a numeric length
property, I'd check for these like this:
typeof obj !== 'undefined' && obj !== null && typeof obj.length === 'number'
Please note that strings will pass this check, which might lead to problems as IE doesn't allow access to a string's characters by index. Therefore, you might want to change typeof obj !== 'undefined'
to typeof obj === 'object'
to exclude primitives and host objects with types distinct from 'object'
alltogether. This will still let string objects pass, which would have to be excluded manually.
In most cases, what you actually want to know is whether you can iterate over the object via numeric indices. Therefore, it might be a good idea to check if the object has a property named 0
instead, which can be done via one of these checks:
typeof obj[0] !== 'undefined' // false negative for `obj[0] = undefined`
obj.hasOwnProperty('0') // exclude array-likes with inherited entries
'0' in Object(obj) // include array-likes with inherited entries
The cast to object is necessary to work correctly for array-like primitives (ie strings).
Here's the code for robust checks for JS arrays:
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
and iterable (ie non-empty) array-like objects:
function isNonEmptyArrayLike(obj) {
try { // don't bother with `typeof` - just access `length` and `catch`
return obj.length > 0 && '0' in Object(obj);
}
catch(e) {
return false;
}
}
python: how to identify if a variable is an array or a scalar
>>> import collections.abc
>>> isinstance([0, 10, 20, 30], collections.abc.Sequence)
True
>>> isinstance(50, collections.abc.Sequence)
False
note: isinstance
also supports a tuple of classes, check type(x) in (..., ...)
should be avoided and is unnecessary.
You may also wanna check not isinstance(x, (str, unicode))
As noted by @2080 and also here this won't work for numpy
arrays. eg.
>>> import collections.abc
>>> import numpy as np
>>> isinstance((1, 2, 3), collections.abc.Sequence)
True
>>> isinstance(np.array([1, 2, 3]), collections.abc.Sequence)
False
In which case you may try the answer from @jpaddison3:
>>> hasattr(np.array([1, 2, 3]), "__len__")
True
>>> hasattr([1, 2, 3], "__len__")
True
>>> hasattr((1, 2, 3), "__len__")
True
However as noted here, this is not perfect either, and will incorrectly (at least according to me) classify dictionaries as sequences whereas isinstance
with collections.abc.Sequence
classifies correctly:
>>> hasattr({"a": 1}, "__len__")
True
>>> from numpy.distutils.misc_util import is_sequence
>>> is_sequence({"a": 1})
True
>>> isinstance({"a": 1}, collections.abc.Sequence)
False
You could customise your solution to something like this, add more types to isinstance
depending on your needs:
>>> isinstance(np.array([1, 2, 3]), (collections.abc.Sequence, np.ndarray))
True
>>> isinstance([1, 2, 3], (collections.abc.Sequence, np.ndarray))
True
Check if all values of array are equal
const allEqual = arr => arr.every( v => v === arr[0] )
allEqual( [1,1,1,1] ) // true
Or one-liner:
[1,1,1,1].every( (val, i, arr) => val === arr[0] ) // true
Array.prototype.every (from MDN) :
The every()
method tests whether all elements in the array pass the test implemented by the provided function.
How do I check if an array includes a value in JavaScript?
Modern browsers have Array#includes
, which does exactly that and is widely supported by everyone except IE:
console.log(['joe', 'jane', 'mary'].includes('jane')); //true
Related Topics
How to Access Discriminator Field from PHP in Doctrine2
In PHP How Does Usort() Function Works
How to Set Current Page "Active" in PHP
Automatically Refresh Token Using Google Drive API with PHP Script
Sending Correct File Size with PHP Download Script
Inserting Utf-8 Encoded String into Utf-8 Encoded MySQL Table Fails with "Incorrect String Value"
Regular Expression and Forward Slash
Eloquent Many-To-Many-To-Many - How to Load Distant Relation Easily
JSON_Decode() Returns Null Issues
PHP Float Calculation Error When Subtracting
Laravel - How to Get Current User in Appserviceprovider
How to Send Cookies with File_Get_Contents
Xml Creation Using Codeigniter
Load Block Outside Magento, and Apply Current Template