Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log only the elements from second level array from a multidimentional array

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!

like image 991
Radu Orza Avatar asked Jun 25 '26 12:06

Radu Orza


2 Answers

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);
like image 199
CertainPerformance Avatar answered Jun 28 '26 00:06

CertainPerformance


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);
like image 33
Nina Scholz Avatar answered Jun 28 '26 00:06

Nina Scholz