How to get the array index in Lodash _.each

Spirit :

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
})
Itay Grudev :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=160781&siteId=1