5

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(); 
huisleona
  • 85
  • 1
  • 10

4 Answers4

3

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]]]]]);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

You just have a couple issues. You need to check the length of your nested arrays and you need to move your code that checks whether a number is even or not inside the array.

 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].length; j++) {
      var evenNumbers = nestedArr[i][j]
      if (evenNumbers % 2 == 0) {
        console.log(evenNumbers)
      }
    }
  }
Bert
  • 80,741
  • 17
  • 199
  • 164
2

You can do this more easy using filter method which accepts a callback method.

var nestedArr = [[1,2,3],[4,5,6],[7,8],[9,10,11,12]];
var mergedArray=[].concat.apply([], nestedArr);
console.log(mergedArray.filter(a => a%2 == 0));
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
  • Thanks! This is really interesting as it prints out an array. I was wondering how to approach it if it requires to print out each value? – huisleona Jun 18 '17 at 18:14
1

You can use reduce with every for something quick.

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

var sift = nestedArr.reduce(function(r,o) {
    o.every(i => i % 2 === 0 ? r.push(i) : true)
    return r;
}, []);

console.log(sift);

If you want a one-liner you can use ReduceRight with Filter

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

var sift = nestedArr.reduceRight((p, b) => p.concat(b).filter(x => x % 2 === 0), []);

console.log(sift)
Rick
  • 1,035
  • 10
  • 18