Javascript Nested arrays even return numbers

I am trying to write a function that prints only even numbers from a nested array. Here is my attempt and it returns "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(); 
+5
source share
4 answers

You can use a recursive approach if the element is an array. You need to transfer the uniformity test inside 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]]]]]); 

Callback solution

 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]]]]]); 
+3
source

You just have a couple of questions. You need to check the length of your nested arrays, and you need to move the code, which checks if the 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) } } } 
+2
source

You can do this more easily by using the filter method, which takes 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)); 
+1
source

You can use shorthand with each 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 to use a single layer, you can use ReduceRight with a 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) 
0
source

Source: https://habr.com/ru/post/1268940/


All Articles