w3resource

JavaScript: Build an array, using an iterator function and an initial seed value

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

Write a JavaScript program to build  an array, using an iterator function and an initial seed value.

  • Use a while loop and Array.prototype.push() to call the function repeatedly until it returns false.
  • The iterator function accepts one argument (seed) and must always return an array with two elements ([value, nextSeed]) or false to terminate.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const unfold = (fn, seed) => {
  let result = [],
    val = [null, seed];
  while ((val = fn(val[1]))) result.push(val[0]);
  return result;
};
var f = n => (n > 50 ? false : [-n, n + 10]);
console.log(unfold(f, 10));

Sample Output:

[-10,-20,-30,-40,-50]

Flowchart:

flowchart: Build an array, using an iterator function and an initial seed value

Live Demo:

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


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to get every element that exists in any of the two arrays once.
Next: Write a JavaScript program to unflatten an object with the paths for keys.

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

Randomizes the order of the values of an array, returning a new array

Example:

const tips_shuffle = ([...arr]) => {
  let x = arr.length;
  while (x) {
    const i = Math.floor(Math.random() * x--);
    [arr[x], arr[i]] = [arr[i], arr[x]];
  }
  return arr;
};
const foo = [2, 4, 6];
console.log(tips_shuffle(foo)); 

Output:

[4, 2, 6]

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook