I have the following array and I need to log only the elements from the second level array from it.
var myArr = [1, 2, 3, [10, 11,[1321,3213,[321321, true], "ha"], 133], 4, 5];
The output should be:
mySecondArr = [10, 11, 133];
with the following code, the output will include the third grade and so on arrays
for(i = 0; i < myArr.length; i++){
if (typeof(myArr[i]) == 'object'){
console.log(myArr[i])
}
}
Thank you in advance!
You can filter by Array.isArray:
const findInnerArr = outerArr => outerArr.find(item => Array.isArray(item));
const myArr = [1, 2, 3, [10, 11,[1321,3213,[321321, true], "ha"], 133], 4, 5];
const output = findInnerArr(myArr)
.filter(item => !Array.isArray(item));
console.log(output);
For more 2nd levels, you could filter by array and filter the inner arrays out and concat the result to a single array.
var array = [1, 2, 3, [10, 11, [1321, 3213, [321321, true], "ha"], 133], ['foo', 'bar', ['baz']], 4, 5],
result = array
.filter(Array.isArray)
.map(a => a.filter(b => !Array.isArray(b)))
.reduce((r, a) => r.concat(a));
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With