Underscore.js _.cycle() Method

The _.cycle() Method takes an integer value and an array which is then used to build an array containing the number of iterations through the given array, strung end-to-end.

A new array created contains the given array number of given times.

Syntax:

_.cycle(integer, array);

Parameters:

  • integer: The number of times given array is iterated.
  • array: The array which is iterated to make a new array

Return Value: This method returns a cycled array.



Note: This will not work in normal JavaScript because it requires the underscore.js contrib library to be installed.

underscore.js contrib library can be installed using npm install underscore-contrib –save

Example: In this example, we will simply create a cycled array using this method.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
// Integer
var int = 10;
// Array
var arr = [1, 2, 3];
// Constructing cycled array
var c_arr = _.cycle(int, arr);
console.log("cycled array : ");
console.log(c_arr);

chevron_right


Output:

cycled array :
[
  1, 2, 3, 1, 2, 3, 1, 2, 3,
  1, 2, 3, 1, 2, 3, 1, 2, 3,
  1, 2, 3, 1, 2, 3, 1, 2, 3,
  1, 2, 3
]

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.