Wednesday, 14 November 2018

In Javascript how do I detect different kinds of elements in an array containing sub arrays and single elements?




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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...