0

Is it possible to distinguish an array from an array of arrays or array of objects in jQuery?

var a = [1,2,3];
var a2 = [[12,'Smith',1],[13,'Jones',2]];
var a3 = [{val:'12', des:'Smith', num:1}];

//a = array
//a2 and a3 = multidimensional array

How can I do this? Thanks

1
  • 1
    Also note that this has absolutely nothing to do with jQuery Commented Nov 15, 2016 at 11:06

3 Answers 3

4

Since you're using jQuery, you can use:

$.isArray(a[0]);

Here's the documentation: http://api.jquery.com/jquery.isarray/

This is definitely not the only way to find out. You could do this in pure JS too, using:

Array.isArray(v[0]);
Sign up to request clarification or add additional context in comments.

3 Comments

Array.isArray for pure JS
$.isArray === Array.isArray, they're the same thing, err
@vic3685 - Thanks
2

Very raw way of checking:

function isMultiDimensional(array) {
  return array.some(element => Array.isArray(element))
}

This basically checks if any of your elements is also an array

If you consider multidimensional arrays where all elements are arrays, look at the other answers.

Comments

0

This function can solve your problem

 function checkArray(arr){
      if(!Array.isArray(arr[0])) return 'simple array';
      else  return 'Not simple array [Array of arrays (or) Array of objects]';
 }

 checkArray(a);    // simple array
 checkArray(a1);    // Not simple array [Array of arrays (or) Array of objects]

3 Comments

I (respectfully) disagree with this; an array of arrays is, for all practical purposes, a multidimensional array. The fact language itself doesn't have a specific concept of multidimensional arrays is mere technicality.
Ya.. So do u mean that array of arrays is a multi dimensional array ?
Not neccessarily, but "array of arrays" is the closest thing a weakly-typed language can have to a multidimensional array. This is why I feel that saying is not supported by JavaScript is not correct.

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.