How to use the range function from lodash

Find comprehensive JavaScript lodash.range code examples handpicked from public code repositorys.

Lodash.range is a function that creates an array of numbers in a given range with optional step and end values.

5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
* // => [0, 1, 2, 3]
*
* _.range(1, 5);
* // => [1, 2, 3, 4]
*
* _.range(0, 20, 5);
* // => [0, 5, 10, 15]
*
* _.range(0, -4, -1);
* // => [0, -1, -2, -3]
fork icon73
star icon711
watch icon29

+ 11 other calls in file

310
311
312
313
314
315
316
317
318
319
module.exports.pullAllWith         = _.pullAllWith;
module.exports.pullAt              = _.pullAt;
module.exports.quaternary          = _.quaternary;
module.exports.rCurry              = _.rCurry;
module.exports.random              = _.random;
module.exports.range               = _.range;
module.exports.rangeRight          = _.rangeRight;
module.exports.rcurry2             = _.rcurry2;
module.exports.rcurry3             = _.rcurry3;
module.exports.rearg               = _.rearg;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

How does lodash.range work?

lodash.range works by taking two or three inputs: a starting value, an optional end value, and an optional step value.

The function generates an array of numbers beginning with the starting value and incrementing by the step value until it reaches the end value or exceeds it.

If the end value is not provided, the function generates an array that includes the starting value but has no defined end.

If the step value is not provided, the function defaults to a step of 1, meaning the array contains sequential integers.

The resulting array can be used for iteration, mathematical operations, or other purposes.

273
274
275
276
277
278
279
280
281
282

var updateProduct;

it('can POST products with a bearer token, some published', function(done) {
  // range is exclusive at the top end, I want 10 things
  var nths = _.range(1, 11);
  return async.eachSeries(nths, function(i, callback) {
    http('/api/v1/products', 'POST', {}, {
      title: 'Cool Product #' + i,
      published: !!(i & 1),
fork icon20
star icon95
watch icon0

879
880
881
882
883
884
885
886
887
888
889
890
891
892


}


Utils.serialVersion = Utils.protocolVersion;


Utils.range = _.range;


Utils._id = _id;
Utils._ttl = _ttl;
Utils._putTime = _putTime;
fork icon9
star icon8
watch icon0

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const _ = require("lodash");

// Create an array of numbers from 1 to 5
const array1 = _.range(1, 6);

console.log(array1); // [1, 2, 3, 4, 5]

// Create an array of even numbers from 2 to 10
const array2 = _.range(2, 11, 2);

console.log(array2); // [2, 4, 6, 8, 10]

// Create an array of numbers from 0 to 4
const array3 = _.range(5);

console.log(array3); // [0, 1, 2, 3, 4]

In this example, we use the lodash.range function to create three different arrays of numbers in a given range. In the first example, we create an array of numbers from 1 to 5 by calling _.range(1, 6). This generates an array that includes the starting value 1 and increments by 1 until it reaches the end value 6, which is not included in the array. In the second example, we create an array of even numbers from 2 to 10 by calling _.range(2, 11, 2). This generates an array that includes the starting value 2 and increments by 2 until it reaches the end value 11, which is not included in the array. In the third example, we create an array of numbers from 0 to 4 by calling _.range(5). This generates an array that includes the starting value 0 and increments by 1 until it reaches the end value 5, which is not included in the array.

24
25
26
27
28
29
30
31
32
33
s = [0, ...s, _.last(s)+3]
let w = s.map(x => 0);
w[0] = 1;

for (let i of _.range(1, s.length)) {
  for (let j of _.range(i-3, i)) {
    if (s[j] >= s[i] - 3) {
      w[i] += w[j];
    }
  }
fork icon1
star icon4
watch icon3

+ 3 other calls in file

126
127
128
129
130
131
132
133
134
135
//   clog(y, x)
//   remaining.delete(tile)
//   clog("T", tile)
//   grid[y][x] = rotateGrid(tile, 4-tile.borders.indexOf(top))
//   clog("g", grid[y][x])
//   for (let x1 of _.range(centerLen)) {
//     for (let y1 of _.range(centerLen)) {
//       boolGrid[centerLen * y + y1][centerLen*x + x1] = grid[y][x].center[y1][x1]
//     }
//   }
fork icon1
star icon4
watch icon3

+ 15 other calls in file

24
25
26
27
28
29
30
31
32
33
let hist = {}
for (let i=0; i<L.length-1; i++) {
  hist[L[i]] = i;
}
let last = L[L.length-1];
for (let i of _.range(L.length, 2020)) {
  let speak = 0;
  if (hist[last] !== undefined) {
    speak = i-hist[last]-1
  }
fork icon1
star icon4
watch icon3

25
26
27
28
29
30
31
32
33
34
for (let i=0; i<L.length-1; i++) {
  hist.set(L[i], i);
}
let last = L[L.length-1];
let T = 30000000;
for (let i of _.range(L.length, T)) {
  let speak = 0;
  if (hist.has(last)) {
    speak = i-hist.get(last)-1
  }
fork icon1
star icon4
watch icon3

20
21
22
23
24
25
26
27
28
29
    solve(L.map(line => int(line)))
  })

function transform(subject, loopSize) {
  let val = 1;
  for (let i of _.range(loopSize)) {
    val = (val * subject)%20201227
  }
  return val
  // subject ^ loopSize mod 20201227
fork icon1
star icon4
watch icon3

947
948
949
950
951
952
953
954
955
956
957
958
959
console.log(property({ 'a': 1 })); // => 1


const propertyOf = _.propertyOf({ 'a': { 'b': 2 } });
console.log(propertyOf({ 'a': { 'b': 2 } })); // => 2


const range = _.range(4);
console.log(range); // => [0, 1, 2, 3]


const rangeRight = _.rangeRight(-4);
console.log(rangeRight); // => [0, -1, -2, -3]
fork icon0
star icon4
watch icon0

+ 15 other calls in file

498
499
500
501
502
503
504
505
506
507
    uuid: generateUUID(),
  }));

const textIndexSentenceMap = Object.fromEntries(sections.flatMap((section) =>
  section.sentenceList.flatMap((sent) =>
    range(sent.textSpan.start, sent.textSpan.ending).map((textIndex) =>
      [textIndex, sent]))));
tok2char
  .forEach(function (indices) {
    const start = indices[0];
fork icon2
star icon3
watch icon0

+ 5 other calls in file

700
701
702
703
704
705
706
707
708
709
vertexCol.insert(_.range(1, numVertices + 1).map((i) => ({_key: "" + i})));

// create a balanced binary tree on edgeCol
edgeCol.insert(
  // for every v._key from col
  _.range(1, numVertices + 1)
    // calculate child indices of (potential) children
    .map(i => [{from: i, to: 2 * i}, {from: i, to: 2 * i + 1}])
    // flatten
    .reduce((accum, cur) => accum.concat(cur), [])
fork icon809
star icon0
watch icon340

+ 2 other calls in file

593
594
595
596
597
598
599
600
601
var interv = [];

console.time('=H=', 'his', 'Got history in');

if ( _.isUndefined(range) || range === null)
	interv = _.range(this.stats.block.number - 1, this.stats.block.number - MAX_HISTORY_UPDATE);

if (!_.isUndefined(range.list))
	interv = range.list;
fork icon353
star icon327
watch icon28

+ 3 other calls in file

1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
  serverJobs.failJobSequence(job_sequence_id);
  return;
}

async.eachSeries(
  _.range(count * test_types.length),
  (iter, callback) => {
    let type = test_types[iter % test_types.length];
    job.verbose(`Test ${Math.floor(iter / test_types.length) + 1}, type ${type}`);
    module.exports._runTest(
fork icon251
star icon248
watch icon14

+ 4 other calls in file

186
187
188
189
190
191
192
193
194
195
const stream = client.query(copy(sql))
stream.on('error', callback)
stream.pipe(
  concat(function (buf) {
    const res = buf.toString('utf8')
    const exp = _.range(0, generateRows + 1).join('\n') + '\n'
    assert.equal(res, exp, 'clientReuse: sent & received buffer should be equal')
    currentRunNumber++
    callback()
  })
fork icon41
star icon297
watch icon7

205
206
207
208
209
210
211
212
213
214
})
.then(async subjects => {
    return await Promise
        .map(subjects, async (subject) => {
            let round = Math.ceil(subject.courses_count/7)
            const r = range(1, ++round);
            return await Promise
                .map(r, async index => {
                    ms.update('info', { text: `scraping... ${this.url}/subjects/${subject.slug}/index?page=${index}` });
                    let json = await this._request({ url: `${this.url}/subjects/${subject.slug}/index?page=${index}` })
fork icon0
star icon4
watch icon1

+ 2 other calls in file

331
332
333
334
335
336
337
338
339
340
        var obj = accumulator.currentObject();
        var length = obj.length;
        var localStart = (start < 0) ? Math.max(0, start + length) : Math.min(length, start);
        var localEnd = (end === null) ? length : end;
        localEnd = (localEnd < 0) ? Math.max(0, localEnd + length) : Math.min(length, localEnd);
        var range = _.range(localStart, localEnd, step);
        this.traceProperties(range, accumulator);
    };
},
tracePropertyGen: function (property) {
fork icon0
star icon1
watch icon1

+ 35 other calls in file

141
142
143
144
145
146
147
148
149
    return false
  }
}

var createLineDoc = main.createLineDoc = function (lines) {
  return _.range(lines).map(function () {
    return ''
  })
}
fork icon0
star icon1
watch icon2

7
8
9
10
11
12
13
14
15
16
17
18
19
var _ = require('lodash');


function makepuzzle(board) {
	var puzzle  = [];
	var deduced = makeArray(81, null);
	var order   = _.range(81);


	shuffleArray(order);


	for (var i = 0; i < order.length; i++) {
fork icon0
star icon0
watch icon1

448
449
450
451
452
453
454
455
456
 * @param mixedCase? {boolean} Whether the letter can be either upper or lower cased. Defaults to true.
 * @return {any}
 */
randomLetters(length = 10, mixedCase = true) {
    length = Math.max(1, Math.min(500, length));
    return _.range(length)
        .map((i) => this.randomLetter(mixedCase))
        .join("");
},
fork icon0
star icon0
watch icon1

+ 4 other calls in file

Other functions in lodash

Sorted by popularity

function icon

lodash.get is the most popular function in lodash (7670 examples)