Lodash: how to move between starting value and ending value

I have a for loop in javascript shown below. How to convert it to lodash for loop? In such scenarios is using lodash beneficial for javascript for the loop?

I have not used lodash much. From here, please advice.

for (var start = b, i = 0; start < end; ++i, ++start) {
// code goes here
}
+4
source share
3 answers

I will imagine that b = 3and end = 10if I run your code and print the variables, here is what I get:

var b = 3;
var end = 10;

for (var start = b, i = 0; start < end; ++i, ++start) {
  console.log(start, i);
}

> 3 0
> 4 1
> 5 2
> 6 3
> 7 4
> 8 5
> 9 6

To accomplish this with lodash (or underscore), I will first create an array with range, then iterate over it and get the index at each iteration.

Here is the result

var b = 3;
var end = 10;

// this will generate an array [ 3, 4, 5, 6, 7, 8, 9 ]
var array = _.range(b, end); 

// now I iterate over it
_.each(array, function (value, key) {
  console.log(value, key);
});

. , ( ).

+4

, lodash for (, ), :

for (var i = 0; i < end - b; i++) {
      var start = i + b;
      // code goes here
}
0

You can use lodash range
https://lodash.com/docs/4.17.4#range

_.range(5, 10).forEach((current, index, range) => {
    console.log(current, index, range)
})

// 5, 0, [5, 6, 7, 8, 9, 10]
// 6, 1, [5, 6, 7, 8, 9, 10]
// 7, 2, [5, 6, 7, 8, 9, 10]
// 8, 3, [5, 6, 7, 8, 9, 10]
// 9, 4, [5, 6, 7, 8, 9, 10]
// 10, 5, [5, 6, 7, 8, 9, 10]
0
source

All Articles