I want to print Fibonacci Series using map() or reduce() function in Javascript. I am not able to find anything online for it. I am not quite sure on what my condition would be in the map().
I am basically writing
fib(n){
return new Array(n-1).fill(1).map((_,i) => *This is where I am confused* ) ;
}
It's relatively easy to do this with reduce()
, just check for the index and act accordingly:
function fib(n){
return new Array(n).fill(1).reduce((arr, _ ,i) => {
arr.push((i <= 1) ? i : arr[i-2] + arr[i-1])
return arr
},[]) ;
}
console.log(fib(10))
map()
is not an especially good fit because you don't have a natural way to access the earlier states.