Abhinav I Abhinav I - 7 months ago 19
Javascript Question

How generate a range of numbers using underscore.js with leading 0s?

I've been trying to generate values for a dropdown where the user is to select hours, minutes.

To get the possible values of minutes, I was using this:

_.range(1, 61)


This generates an array like

[1, 2, 3 ... 60]


but I require it to be of form

[01, 02, 03 ... 60]


Is there a clean way to getting this using underscore?.

Answer

Place this at the top of your javascript file ...

Number.prototype.pad = function (count) {
   var num = this.valueOf();
   var ret = "";
   for (var i = 0; i < count - num.toString().length; i++) {
       ret += "0";
   }
   ret += num;
   return ret;
}

Then return ...

_.range(1, 61).map(function (num) { return num.pad(2) })

This will give an array of strings with leading 0s of length 2