Underscore: array function: repeat val x times

Created on 21 Nov 2012  ·  4Comments  ·  Source: jashkenas/underscore

suggested impl:

_.repeat("0",10)
// => ["0","0",... 10 times]

or alternatively, modify _.range function so that:

_.range(0,0,10), instead of outputting [] outputs the above.

Here is the use case:

var values = ["A","B","C"];
_.object(values)
// => {"A":undefined,"B":undefined,"C":undefined} // wonderful, as expected

But, what if i want to initialize every value in the key/value pairs to the same value?
This could be another option but doesn't work:

_.object(values,"0") // provide scalar instead of array
// => {"A":undefined,"B":undefined,"C":undefined} // same as before

This would work if _repeat existed:

_.object(values,_.repeat("0",values.length))
// => {"A":"0","B":"0","C":"0"} 
change

Most helpful comment

Instead of another method we could just mod _.times to return the result of each callback call, like Lo-Dash does:

var zeros = _.times(10, function() { return 0; });
// => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

All 4 comments

+1 for an array repeat function. I wouldn't modify _.range for that, since it is dedicated to number ranges.

Instead of another method we could just mod _.times to return the result of each callback call, like Lo-Dash does:

var zeros = _.times(10, function() { return 0; });
// => [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

+1 @jdalton.

Sounds good to me -- go for it.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

xiaoliwang picture xiaoliwang  ·  3Comments

marcalj picture marcalj  ·  5Comments

jdalton picture jdalton  ·  4Comments

jezen picture jezen  ·  8Comments

Francefire picture Francefire  ·  5Comments