1

I was wondering if there was an easier / cleaner way to expand one integer 6 and make it into an array of numbers [1, 2, 3, 4, 5, 6].

This is what I've got and I hate it.

var pages = function(number_int){
    var numbers_array = [];
    for (var i = 1; i <= number_int; i++) {
        numbers_array.push(i);
    }
    return numbers_array;
};

I'd love to use underscore if I can.

ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • 1
    This is really a question for [codereview.se], but it's so trivial I don't think it should be migrated. –  Oct 24 '13 at 19:49
  • Yeah you're right, but if I posted it to code review, no one would have saw it. – ThomasReggi Oct 24 '13 at 19:51
  • 1
    http://stackoverflow.com/questions/3746725/create-a-javascript-array-containing-1-n – georg Oct 24 '13 at 21:26

2 Answers2

5

Look at the range function in underscore.js

Farmer Joe
  • 6,020
  • 1
  • 30
  • 40
2

The range function in Underscore.js is pretty handy.

Here is the definition:

_.range([start], stop, [step])
  • start: optional, default 0
  • stop : mandatory
  • step : optional, default 1

Note : range generates values in the range start(inclusive) and stop(exclusive)

So, if number_int = 6 in your case, to generate [1, 2, 3, 4, 5, 6] you must use the range function by specifying stop as number_int + 1

Final Answer:

var pages = function(number_int){
    var numbers_array = [];
    numbers_array = _.range(1,number_int + 1);
    return numbers_array;
};

JSFiddle: https://jsfiddle.net/dineshchitlangia/xj8q5bea/4/