[javascript] Create array of all integers between two numbers, inclusive, in Javascript/jQuery

Say I have the following checkbox:

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

To get the two numbers that define the boundaries of 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 then create an array that contains all integers between lowEnd and highEnd, including lowEnd and highEnd themselves? For this specific example, obviously, the resulting array would 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]

This question is related to javascript jquery arrays

The answer is


My five cents:

Both direction array of integers function.

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

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

Based on this answer.

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

  return (isReverse) ? result.reverse() : result;
}

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


function range(j, k) { 
    return Array
        .apply(null, Array((k - j) + 1))
        .map(function(_, n){ return n + j; }); 
}

this is roughly equivalent to

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;
}

breaking it down:

var targetLength = (k - j) + 1;

var a = Array(targetLength);

this creates a sparse matrix of the correct nominal length. Now the problem with a sparse matrix is that although it has the correct nominal length, it has no actual 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 produces a dense matrix of (actual) length targetLength, where all elements have undefined value. The first argument is the 'this' value for the the array constructor function execution context, and plays no role here, and so is null.

So now,

 console.log(b);

yields

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

finally

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

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

So then

console.log(c);

yields

 Array [ 7, 8, 9, 10, 11, 12, 13 ]

ES6 :

Use Array.from (docs here):

_x000D_
_x000D_
console.log(
   Array.from({length:5},(v,k)=>k+1)
)
_x000D_
_x000D_
_x000D_


My version of the loop ;)

var lowEnd = 1;
var highEnd = 25;
var arr = [];
while(lowEnd <= highEnd){
   arr.push(lowEnd++);
}

I highly recommend underscore or lo-dash libraries:

http://underscorejs.org/#range

(Almost completely compatible, apparently lodash runs quicker but underscore has better doco IMHO)

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

Both libraries have bunch of very useful utilities.


You can design a range method that increments a 'from' number by a desired amount until it reaches a 'to' number. This example will 'count' up or down, depending on whether from is larger or smaller than to.

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 ever want to step by a decimal amount : Array.range(0,1,.01) you will need to truncate the values of any floating point imprecision. Otherwise you will return numbers like 0.060000000000000005 instead of .06.

This adds a little overhead to the other 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;
    }   
}

Adding http://minifiedjs.com/ to the list of answers :)

Code is similar to underscore 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 low footprint and easy to understand syntax. For me, it is a replacement for jQuery, MustacheJS and Underscore/SugarJS in one framework.

Of course, it is not that popular as underscore. This might be a concern for some.

Minified was made available by Tim Jansen using the CC-0 (public domain) license.


_x000D_
_x000D_
        function getRange(a,b)_x000D_
        {_x000D_
            ar = new Array();_x000D_
            var y = a - b > 0 ? a - b : b - a;_x000D_
            for (i=1;i<y;i++)_x000D_
            {_x000D_
                ar.push(i+b);_x000D_
            }_x000D_
            return ar;_x000D_
        }
_x000D_
_x000D_
_x000D_


function createNumberArray(lowEnd, highEnd) {
    var start = lowEnd;
    var array = [start];
    while (start < highEnd) {
        array.push(start);
        start++;
    }
} 

If the start 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 be able to take a third argument to be able to modify the step used to build the array, and to make it work even though the start 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]

This way the function accepts positive and negative steps and if no step is given, it defaults to 1.


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's probably a DRYer way to do the loop, but that's the basic idea.


Solving in underscore

data = [];
_.times( highEnd, function( n ){ data.push( lowEnd ++ ) } );

In JavaScript ES6:

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

For completeness, here it is with an optional step parameter.

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

I would use range-inclusive from npm in an actual project. It even supports backwards steps, so that's cool.


fastest way

  1. while-- is faster on most browsers
  2. direct setting a variable 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 THE DOWNVOTERS

performance

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

faster in ie and 3x faster in firefox

only on aipad air the for loop is a little faster.

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

with chrome,ff,ie,safari,mobile safari.

i would like to see the performance on older ie browsers where the for loop isn't that optimized!


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?