Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Nested Array Return Even Numbers

I am trying to write a function that prints only the even numbers from a nested array. Here is my attempt and it keeps returning "undefined".

function printEvents(){

 var nestedArr = [[1,2,3],[4,5,6],[7,8],[9,10,11,12]];

  for (var i = 0; i<nestedArr.length; i++) {
    for (var j = 0; j<nestedArr[i]; j++) {
      var evenNumbers = nestedArr[i][j]
    }
  }

  if (evenNumbers % 2 == 0) {
    console.log(evenNumbers)
  }

 }

 printEvents(); 
like image 299
huisleona Avatar asked Jun 17 '17 20:06

huisleona


1 Answers

You could use a recursive approach, if the item is an array. You need to move the test for evenness inside of the for loop.

function printEvents(array) {
    var i;
    for (i = 0; i < array.length; i++) {
        if (Array.isArray(array[i])) {
            printEvents(array[i]);
            continue;
        }
        if (array[i] % 2 == 0) {
            console.log(array[i]);
        }
    }
}

printEvents([[1, 2, 3], [4, 5, 6], [7, 8], [9, 10, 11, 12], [[[13, [14]]]]]);

Solution with a callback

function getEven(a) {
    if (Array.isArray(a)) {
        a.forEach(getEven);
        return;
    }
    if (a % 2 == 0) {
        console.log(a);
    }
}

getEven([[1, 2, 3], [4, 5, 6], [7, 8], [9, 10, 11, 12], [[[13, [14]]]]]);
like image 145
Nina Scholz Avatar answered Oct 20 '22 00:10

Nina Scholz