w3resource

JavaScript: Generate an array, containing the Fibonacci sequence, up until the nth term

JavaScript fundamental (ES6 Syntax): Exercise-237 with Solution

Write a JavaScript program to generate an array, containing the Fibonacci sequence, up until the nth term.

  • Use Array.from() to create an empty array of the specific length, initializing the first two values (0 and 1).
  • Use Array.prototype.reduce() and Array.prototype.concat() to add values into the array, using the sum of the last two values, except for the first two.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const fibonacci = n =>
  Array.from({ length: n }).reduce(
    (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
    []
  );
console.log(fibonacci(2)); 
console.log(fibonacci(3)); 
console.log(fibonacci(6));

Sample Output:

[0,1]
[0,1,1]
[0,1,1,2,3,5]

Flowchart:

flowchart: Generate an array, containing the Fibonacci sequence, up until the nth term.

Live Demo:

See the Pen javascript-basic-exercise-237-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to get the first key that satisfies the provided testing function. Otherwise return undefined.
Next: Write a JavaScript program to calculate the factorial of a number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

JavaScript: Tips of the Day

Creates an object composed of the properties the given function returns truthy for. The function is invoked with two arguments: (value, key)

Example:

const tips_composed = (obj, fn) =>
  Object.keys(obj)
    .filter(k => fn(obj[k], k))
    .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});

console.log(tips_composed({ p: 2, q: '4', r: 6 }, x => typeof x === 'number'));

Output:

[object Object] {
  p: 2,
  r: 6
}