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]
Answer
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]
No comments:
Post a Comment