Possible Duplicate:
How to detect if a variable is an array
I have a simple question:
How do I detect if a parameter passed to my javascript function is an array? I don't believe that I can test:
if (typeof paramThatCouldBeArray == 'array')
So is it possible?
How would I do it?
Thanks in advance.
To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.
Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.
function checkIfArrayIsUnique(myArray) { for (var i = 0; i < myArray. length; i++) { for (var j = 0; j < myArray. length; j++) { if (i != j) { if (myArray[i] == myArray[j]) { return true; // means there are duplicate values } } } } return false; // means there are no duplicate values. }
Answer: Use the Array. isArray() Method isArray() method to check whether an object (or a variable) is an array or not. This method returns true if the value is an array; otherwise returns false .
This is the approach jQuery 1.4.2 uses:
var toString = param.prototype.toString; var isArray = function(obj) { return toString.call(obj) === "[object Array]"; }
if (param instanceof Array) ...
Edit. As of 2016, there is a ready-built method that catches more corner cases, Array.isArray
, used as follows:
if (Array.isArray(param)) ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With