Create an array of all integers between two numbers, inclusive, in Javascript / jQuery

Let's say I have the following flag:

<input type="checkbox" value="1-25" /> 

To get two numbers that define the boundaries of the range I'm looking for, I use the following jQuery:

 var value = $(this).val(); var lowEnd = Number(value.split('-')[0]); var highEnd = Number(value.split('-')[1]); 

How do I create an array containing all integers between lowEnd and highEnd , including lowEnd and highEnd ? For this specific example, the resulting array will obviously be:

 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] 
+64
javascript jquery arrays
Nov 09 '11 at 17:52
source share
15 answers
 var list = []; for (var i = lowEnd; i <= highEnd; i++) { list.push(i); } 
+102
Nov 09 '11 at 17:56
source share

My version of the loop;)

 var lowEnd = 1; var highEnd = 25; var arr = []; while(lowEnd <= highEnd){ arr.push(lowEnd++); } 
+24
Nov 09 '11 at 18:05
source share

I highly recommend underscore libraries or lo-dash

http://underscorejs.org/#range

(apparently, almost completely compatible, lodash is faster, apparently, but underlining is better than doco (IMHO)

_. range ([start], stop, [step])

Not only for this, but also for very useful utilities

+24
Nov 12 '13 at 10:29
source share

In JavaScript ES6:

 function range(start, end) { return Array(end - start + 1).fill().map((_, idx) => start + idx) } var result = range(9, 18); // [9, 10, 11, 12, 13, 14, 15, 16, 17, 18] console.log(result); 

For completeness, here it has an optional step parameter.

 function range(start, end, step = 1) { const len = Math.floor((end - start) / step) + 1 return Array(len).fill().map((_, idx) => start + (idx * step)) } var result = range(9, 18, 0.83); console.log(result); 

I would use range-inclusive from npm in a real project. It even supports reverse steps, so cool.

+21
Oct 31 '15 at 23:07
source share

quick way

  • while - faster in most browsers
  • setting a variable directly is faster than push

function:

 var x=function(a,b,c,d){d=[];c=b-a+1;while(c--){d[c]=b--}return d}, theArray=x(lowEnd,highEnd); 

or

 var arr=[],c=highEnd-lowEnd+1; while(c--){arr[c]=highEnd--} 

EDIT

readable version

 var arr = [], c = highEnd - lowEnd + 1; while ( c-- ) { arr[c] = highEnd-- } 

Demo

http://jsfiddle.net/W3CUn/

FOR LOADERS

performance

http://jsperf.com/for-push-while-set/2

faster in ie and 3 times faster in firefox

only on iPad air does the for loop run a little faster.

tested on win8, osx10.8, ubuntu14.04, ipad, ipad air, ipod;

with chrome, ff, i.e. safari, mobile safari.

I would like to see performance in older browsers where the for loop is not optimized!

+11
Jun 03 '13 at 17:16
source share

Use case

 var genArr=(1)['..'](10) //[1,2,3,4,5,6,7,8,9,10] 

API

 Number.prototype['..']=function(to,step){ var arr = [],from=this; while(from <= to){ arr.push(from++); } return arr; }; 

FIDDLE:

http://jsfiddle.net/abdennour/mcpnvsmm/




ES6:

 console.log( Array.from({length:10},(v,k)=>k+1) ) 
+8
Jan 31 '15 at 1:50
source share
 function range(j, k) { return Array .apply(null, Array((k - j) + 1)) .map(function(_, n){ return n + j; }); } 



it is roughly equivalent

 function range(j, k) { var targetLength = (k - j) + 1; var a = Array(targetLength); var b = Array.apply(null, a); var c = b.map(function(_, n){ return n + j; }); return c; } 

break it:

 var targetLength = (k - j) + 1; var a = Array(targetLength); 

this creates a sparse matrix with the correct nominal length. Now the problem with the sparse matrix is ​​that, although it has the correct nominal length, it does not have real elements, so for

 j = 7, k = 13 console.log(a); 

gives us

 Array [ <7 empty slots> ] 

Then

 var b = Array.apply(null, a); 

passes the sparse matrix as an argument list to the Array constructor, which creates a dense (actual) matrix length targetLength, where all elements are undefined. The first argument is the value of 'this' for the context of the execution of the array constructor function and does not play any role here, and therefore it is null.

So now

  console.log(b); 

gives

  Array [ undefined, undefined, undefined, undefined, undefined, undefined, undefined ] 

finally,

 var c = b.map(function(_, n){ return n + j; }); 

uses the fact that the Array.map function passes: 1. the value of the current element and 2. the index of the current element, delegate / callback of the map. The first argument is discarded, and the second can be used to set the correct sequence value after setting the start offset.

So then

 console.log(c); 

gives

  Array [ 7, 8, 9, 10, 11, 12, 13 ] 
+8
Sep 17 '15 at 15:36
source share

If the beginning is always less than the end, we can do:

 function range(start, end) { var myArray = []; for (var i = start; i <= end; i += 1) { myArray.push(i); } return myArray; }; console.log(range(4, 12)); // β†’ [4, 5, 6, 7, 8, 9, 10, 11, 12] 

If we want to have a third argument, in order to be able to change the step used to assemble the array and make it work, even if the beginning is greater than the end:

 function otherRange(start, end, step) { otherArray = []; if (step == undefined) { step = 1; }; if (step > 0) { for (var i = start; i <= end; i += step) { otherArray.push(i); } } else { for (var i = start; i >= end; i += step) { otherArray.push(i); } }; return otherArray; }; console.log(otherRange(10, 0, -2)); // β†’ [10, 8, 6, 4, 2, 0] console.log(otherRange(10, 15)); // β†’ [10, 11, 12, 13, 14, 15] console.log(otherRange(10, 20, 2)); // β†’ [10, 12, 14, 16, 18, 20] 

Thus, the function takes positive and negative steps, and if no steps are specified, the default value is 1.

+4
Jan 14 '15 at 1:57
source share
 var values = $(this).val().split('-'), i = +values[0], l = +values[1], range = []; while (i < l) { range[range.length] = i; i += 1; } range[range.length] = l; 

There is probably a DRYER method for looping, but that is the main idea.

+3
Nov 09 '11 at 17:55
source share
 function createNumberArray(lowEnd, highEnd) { var start = lowEnd; var array = [start]; while (start < highEnd) { array.push(start); start++; } } 
+3
Nov 09 '11 at 17:56
source share

You can create a range method that increments the number "from" by the desired amount until the number "to" is reached. This example will β€œcount” up or down, depending on whether it is more or less from it.

 Array.range= function(from, to, step){ if(typeof from== 'number'){ var A= [from]; step= typeof step== 'number'? Math.abs(step):1; if(from> to){ while((from -= step)>= to) A.push(from); } else{ while((from += step)<= to) A.push(from); } return A; } } 

If you want to take a decimal step: Array.range (0,1, .01) you need to trim the values ​​of any floating point inaccuracies. Otherwise, you will return numbers like 0.060000000000000005 instead of .06.

This adds a bit of overhead to another version, but works correctly for integer or decimal steps.

 Array.range= function(from, to, step, prec){ if(typeof from== 'number'){ var A= [from]; step= typeof step== 'number'? Math.abs(step):1; if(!prec){ prec= (from+step)%1? String((from+step)%1).length+1:0; } if(from> to){ while(+(from -= step).toFixed(prec)>= to) A.push(+from.toFixed(prec)); } else{ while(+(from += step).toFixed(prec)<= to) A.push(+from.toFixed(prec)); } return A; } } 
+2
Nov 09 '11 at 18:38
source share

Adding http://minifiedjs.com/ to the answer list :)

The code is similar to underscores and others:

 var l123 = _.range(1, 4); // same as _(1, 2, 3) var l0123 = _.range(3); // same as _(0, 1, 2) var neg123 = _.range(-3, 0); // same as _(-3, -2, -1) var empty = _.range(2,1); // same as _() 

Docs here: http://minifiedjs.com/api/range.html

I use minified.js because it solves all my problems with a low trace level and clear syntax. For me, this is a replacement for jQuery, MustacheJS and Underscore / SugarJS in one structure.

Of course, this is not as popular as underlining. This may be a problem for some.

Minified was provided by Tim Jansen under a CC-0 (public domain) license.

+2
Sep 15 '15 at 12:21
source share

My five cents:

A whole array of integers .

When the range (0, 5) becomes [0, 1, 2, 3, 4, 5] .

And the range (5, 0) will become [5, 4, 3, 2, 1, 0] .

Based on this answer.

 function range(start, end) { isReverse = (start > end); var targetLength = isReverse ? (start - end) + 1 : (end - start ) + 1; var arr = new Array(targetLength); var b = Array.apply(null, arr); var result = b.map(function (discard, n) { return (isReverse) ? n + end : n + start; }); return (isReverse) ? result.reverse() : result; } 

PS For use in real life, you should also check args for isFinite() and isNaN() .

+2
Sep 24 '15 at 9:22
source share

  function getRange(a,b) { ar = new Array(); var y = a - b > 0 ? a - b : b - a; for (i=1;i<y;i++) { ar.push(i+b); } return ar; } 
+1
Jul 27 '15 at 5:05
source share

Underscore solution

 data = []; _.times( highEnd, function( n ){ data.push( lowEnd ++ ) } ); 
-one
01 Oct '14 at 6:46
source share



All Articles