0

I have two arrays:

var firstarray = [123, 13, 34, 12, 63, 63];

var secondarray = [[10,20,10], [122, 123, 53], [542, 234, 12, 331]];

I need to have a function that works something like this:

function checkArray(array){
    //if array contains multiple arrays, return true
    //if the array contains only values, return false
}

The number of arrays inside secondarray always varies.

tamarasaurus
  • 439
  • 2
  • 6
  • 9

4 Answers4

4

Hint: Loop on the first array and determine if one of the object you're reading is an array.

Here is a function that could help you :

function is_array(input){
    return typeof(input)=='object'&&(input instanceof Array);
}
Michael Laffargue
  • 10,116
  • 6
  • 42
  • 76
  • Writing a proper "isArray" function is not as simple as it may appear, see [this thread](http://stackoverflow.com/questions/4775722/javascript-check-if-object-is-array) for details. – georg Mar 07 '12 at 09:36
  • -1: Unfortunately that doesn't answer the question. First of all the request was to discover whether the array contained further arrays or just primitive values. Also it won't work for the given data, as `Array(1, 2, 3) instanceof Array` is `true` but '[1, 2, 3] instanceof Array' is `false`. – Borodin Mar 07 '12 at 09:36
  • @Borodin I was not giving the answer but just an hint. And you can see there http://jsfiddle.net/4g3B7/1/ that the function will work. And FYI `[1, 2, 3] instanceof Array` returns `true` – Michael Laffargue Mar 07 '12 at 09:53
1

In modern Javascript:

 myAry.every(Array.isArray) // returns true if all elements of myAry are arrays

References (and replacements for older browsers):

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray

georg
  • 211,518
  • 52
  • 313
  • 390
1

The main problem to this is that in JavaScript typeof anArrayVariable returns object as does typeof aRealObject - so there's no easy way to distinguish them.

jQuery fixes this to some extent with a method $.isArray() which correctly returns true for an array and false for an object, a number, a string or a boolean.

So, using jQuery this becomes as easy as:

function checkArray(array){
    //if array contains multiple arrays, return true
    //if the array contains only values, return false

    for(var i=0;i<array.length;i++){
      if($.isArray(array[i]))   
          return true;
    }
    return false;
}

I suggest you could take a look at the source for that method in jQuery and implement this same idea in vanilla javascript.

Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

Check the type of the first element in the array:

function checkArray(list) {
  return typeof(list[0]) == "object";
}
Borodin
  • 126,100
  • 9
  • 70
  • 144