Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the array index in Lodash _.each

I'm newbie in JavaScript. I have a question

My code in Java:

public void checkArray(int a, int b) {
    int[]days = new int[]{5, 15, 25};
    int[]hours = new int[]{6, 8, 7};
    ArrayList<Interger> result = new ArrayList<>();
    for (int i = 0; i < days.length-1;  i++) {
        if (days[i] < a && b < days[i+1]) {
            result.add(hours[i]);
        } else if (days[i] > a && days[i] < b) {
            result.add(hours[i]);
            if (i > 0) {
                result.add(hours[i-1]);
            }
        }

How can I write this code in JavaScript with Lodash _.each? I can't find a variable like [i] in JavaScript code, so I can't check the condition [if (days[i] < a && b < days[i+1])]

My code in JavaScript:

_.each(days, day => {
    //TODO something
})
like image 694
Spirit Avatar asked Jan 31 '19 22:01

Spirit


2 Answers

From the Lodash documentation:

Iterates over elements of collection and invokes iteratee for each element. The iteratee is invoked with three arguments: (value, index|key, collection). Iteratee functions may exit iteration early by explicitly returning false.

This means that you can simply do:

_.each( days, function( day, i ){

});

So your whole code becomes:

var days = [5, 15, 25];
var hours = [6, 8, 7];
var result = [];

_.each( days, function( day, i ){
    if( days[i] < a && b < days[i+1] ){ // days[i] == day
        result.push( hours[i] );
    } else if( days[i] > a && days[i] < b ){
        result.push( hours[i] );
        if( i > 0 ){
            result.push( hours[i-1] );
        }
    }
})

Here is a jsFiddle to experiment.

like image 62
Itay Grudev Avatar answered Oct 24 '22 05:10

Itay Grudev


From Lodash Documentation:

Iterates over elements of collection and invokes iteratee for each element. The iteratee is invoked with three arguments: (value, index|key, collection). Iteratee functions may exit iteration early by explicitly returning false.

_.each gets only one Collection to iterate as the first argument, and a function "iteratee" for the second argument. So, for is a good option for you.

However, if you still want to use lodash you can get help from _range to create an array of indices, and then you can do something like that:

(in javascript of course)

let days = [5, 15, 25];
let hours = [6, 8, 7];
let result = [];
_.each(_.range(days.length),function(i) {
    if (days[i] < a && b < days[i+1]) {
        result.push(hours[i]);
    } else if (days[i] > a && days[i] < b) {
        result.push(hours[i]);
        if (i > 0) {
            result.push(hours[i-1]);
        }
    }
});
like image 42
SomoKRoceS Avatar answered Oct 24 '22 05:10

SomoKRoceS