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.

1
  • Should you tag this homework ? Commented Mar 7, 2012 at 9:19

4 Answers 4

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Writing a proper "isArray" function is not as simple as it may appear, see this thread for details.
-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 I was not giving the answer but just an hint. And you can see there jsfiddle.net/4g3B7/1 that the function will work. And FYI [1, 2, 3] instanceof Array returns true
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

Comments

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.

Comments

0

Check the type of the first element in the array:

function checkArray(list) {
  return typeof(list[0]) == "object";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.