4

I am being given data in an array that contains sub arrays and single elements. I do not know how many elements in the main array are sub arrays, or how many are single elements, or how many elements will be in a sub array, or where the sub arrays will be in the main array.

Is there a way I can detect the sub arrays or the single elements?

Example:

array[ [1,2,3], 4, 5]
Junco
  • 281
  • 1
  • 4
  • 12

3 Answers3

4

Loop and check:

[1,2,[4,5],3].forEach((item, i) => {
    if (Array.isArray(item)) {
        console.log(`Item ${i} is an array!`); // Item 2 is an array!
    }
})

Or map to booleans:

[1,2,[4,5],3].map(Array.isArray); // [false, false, true, false]
Adrian Lynch
  • 8,237
  • 2
  • 32
  • 40
  • provided you don't need to support legacy javascript engines (really old browsers), this is the correct answer. If you _do_ need to support legacy browsers, add this polyfill: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray – code_monk Dec 17 '15 at 16:27
0

You can use the operator typeof.

typeof 1; //number
typeof 'hola'; //string

Although you keep warning in that typeof array is object. So you need check the class using instanceof method (or the static method Array.isArray(your_variable)). For this issue you can read this question (How do you check if a variable is an array in JavaScript?).

In your particular case

[1, 2, 3, ['a','b']].forEach(function(element){
    if(typeof(element) === 'number'){
       //todo
    }elseif(typeof(element) === 'string'){
      //todo
    }elseif(Array.isArray(element){
        //todo array element
    }
});
Community
  • 1
  • 1
caballerog
  • 2,679
  • 1
  • 19
  • 32
0

Using instanceof:

 for(var i=0;i<your_array.length;i++){
        if(your_array[i] instanceof Array){
               console.log("Subarray!");
        }else{
               console.log("Not Subarray!");
        }
 }