Radu Orza
Radu Orza

Reputation: 33

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!

Upvotes: 3

Views: 98

Answers (8)

segito10
segito10

Reputation: 388

Recursive mode get any level of the array

function getElementsAt(_array, level, currentLvl=1){
  if(level< 1) throw("level must be > 1");
  if(typeof _array === "undefined") throw("Array or level is undefined");

  
  hasSubLvl = _array.some(e=>{
    return e instanceof Array;
  });
  if(currentLvl!== level){
  const __array = _array.filter(e =>{
      return e instanceof Array;
    })[0];
    return getElementsAt(__array, level, currentLvl+1);
  }
  else{
    return !hasSubLvl ? _array : _array.filter(e =>{
    	return !(e instanceof Array);
    });
  }
}

const arr = [1, 2, 3, [10, 11,[1321,3213,[321321, true], "ha"], 133], 4, 5];
const myArr = getElementsAt(arr, 2);

console.log(myArr, "result");

Upvotes: 1

Radu Orza
Radu Orza

Reputation: 33

I've come with a simple solution to my own question, easy to understand for beginers :) thank you all for the help!

 var myArr = [1, 2, 3, [10, 11, [1321, 3213, [321321, true], "ha"], 133], 4, 5];


    for (i = 0; i < myArr.length; i++) {
        if (typeof (myArr[i]) == 'object') {
            var secondArr = arrayulMeu[i]
            for (j = 0; j < secondArr.length; j++) {
                if (typeof (secondArr[j]) != 'object') {
                    console.log(secondArr[j])
                }
            }
        }
    }

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386746

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

Upvotes: 2

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28475

Use Array.filter, Array.reduce and Array.isArray

let myArr = [1, 2, 3, [10, 11,[1321,3213,[321321, true], "ha"], 133], 4, 5, ['this', 'should', ['not'], 'be', 'part', 'of', 'result']];

/* 1. Get all the items that are array from myArr
** 2. Reduce that array with pushing non-Array into the result. */
let result = myArr.filter((a) => Array.isArray(a)).reduce((a,c) => [...a, ...c.filter((d) => !Array.isArray(d))], []);

console.log(result);

Upvotes: 1

Md Johirul Islam
Md Johirul Islam

Reputation: 5162

var myArr = [1, 2, 3, [10, 11,[1321,3213,[321321, true], "ha"], 133], 4, 5];

myArr = myArr.find((data) => typeof(data) ==='object');

myArr = myArr.filter((data) => typeof(data) != 'object');
console.log(myArr);

Upvotes: 0

Alex
Alex

Reputation: 2232

@CertainPerformance did it in the most cleanest and sweetest way.

I've used for-loops to find your result.

var myArr = [1, 2, 3, [10, 11,[1321,3213,[321321, true], "ha"], 133], 4, 5];

let ans = []

for(let i=0;i<myArr.length; i++) {
	if(Array.isArray(myArr[i])) {
		for(let j=0;j<myArr[i].length;j++) {
			if(!Array.isArray(myArr[i][j])) {
				ans.push(myArr[i][j]);
			}
		}
	}
}

console.log(ans);

Upvotes: 0

Ronn Wilder
Ronn Wilder

Reputation: 1368

@CertainPerformance answer looks much better, but still for your reference, this is your way.

var newArr = [];
for(i = 0; i < myArr.length; i++){
    if (typeof(myArr[i]) == 'object'){
        // second level found
        for(var j=0;j<myArr[i].length;j++){
            if(typeof(myArr[i][j]) != 'object'){
                newArr.push(myArr[i][j]);
            }
        }
        break;
    }
}

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371049

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

Upvotes: 8

Related Questions