Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash : how to loop with between a start value and end value

I've a for loop in javascript shown below. How to convert it to lodash for loop? In such scenarios using lodash is advantageous over javascript for loop?

I've not used lodash much. Hence please advice.

for (var start = b, i = 0; start < end; ++i, ++start) {
// code goes here
}
like image 941
Temp O'rary Avatar asked Jul 06 '15 13:07

Temp O'rary


2 Answers

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]
like image 69
iamandrewluca Avatar answered Nov 08 '22 19:11

iamandrewluca


I will imagine that b = 3 and end = 10 if I run your code and print the variables here is what I will 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 perform this with lodash (or underscore) I will first generate an array with range then iterate over it and gets the index on 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);
});

And you will get the same result. The complexity is the same as the previous one (so no performance issue).

like image 25
IxDay Avatar answered Nov 08 '22 19:11

IxDay