I am trying to write a function where the function returns a sub-array of the name and age key/value pairs in the objects in an array. I am to use recursion to achieve it, however I can't find a solution that doesn't involve keeping the num and arr2 variables outside of the function (as when they are inside they default back to zero/empty with every loop).
I have this testing out well in the console however with different arrays I am returning undefined
I am also not sure if my recursive function call is in the right place. Any tips or pointers will be very much appreciated!
var arr =[
{name:'mike', age:22},
{name:'robert', age:12},
{name:'roger', age:44},
{name:'peter', age:28},
{name:'Ralph', age:67}
]
var arr2 = []
var num = 0;
function recursive (arr) {
if (num < arr.length ) {
debugger
arr2.push([arr[num].name, arr[num].age])
num++;
recursive(arr)
}
else if (num === arr.length) {
return arr2;
}
}
This is my desired output:
[[ mike, 22],
[ robert, 12],
[ roger, 44],
[ peter, 28],
[ ralph, 67]]
arr.reduce((a,e) =>(a.push([e.name, e.age]), a), []);