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]
4
  • Bartek: OK - Can you please give me a code example of how I could detect the sub array using that other question with answers? Commented Dec 17, 2015 at 16:18
  • Loop through the array? Commented Dec 17, 2015 at 16:19
  • I tried that. But, when I use array[0] I get 1. I thought I would get that sub array. But, I only get 1. Don't I have to use array[0][0] to get 1 ? Commented Dec 17, 2015 at 16:20
  • This one: stackoverflow.com/a/767496/295783 Commented Dec 17, 2015 at 16:30

3 Answers 3

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

1 Comment

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: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
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!");
        }
 }

Comments

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
    }
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.