Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last iteration in a _.forEach() loop

I got introduced to lodash not too long ago and I'm having what seems to be a simple challenge with it. I am using a _.forEach() loop to perform a function on objects of an Array in typescript. But I need to know when it gets to the last iteration to perform a specific function.

_.forEach(this.collectionArray, function(value: CreateCollectionMapDto) {
      // do some stuff
      // check if loop is on its last iteration, do something.
    });

I checked the documentation for this or anything to do with index but could not find anything. Please help me.

like image 919
Kacey Ezerioha Avatar asked Nov 21 '17 15:11

Kacey Ezerioha


People also ask

How do you end a forEach?

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Does forEach iterate in order?

forEach() method iterates over the array items, in ascending order, without mutating the array. The first argument of forEach() is the callback function called for every item in the array. The second argument (optional) is the value of this set in the callback. Let's see how forEach() works in practice.

What does forEach loop return?

forEach() executes the callbackFn function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.

Which is the fastest while for forEach () for of?

Correctly used, while is the fastest, as it can have only one check for every iteration, comparing one $i with another $max variable, and no additional calls before loop (except setting $max) or during loop (except $i++; which is inherently done in any loop statement).


2 Answers

Hey maybe could you try :

const arr = ['a', 'b', 'c', 'd'];
arr.forEach((element, index, array) => {
    if (index === (array.length -1)) {
        // This is the last one.
        console.log(element);
    }
});

you should use native function as many as possible and lodash when more complexe cases comming

But with lodash you can also do :

const _ = require('lodash');

const arr = ['a', 'b', 'c'];
_.forEach(arr, (element, index, array) => {
    if (index === (array.length -1)) {
        // last one
        console.log(element);
    }
});
like image 103
Adrien De Peretti Avatar answered Sep 20 '22 13:09

Adrien De Peretti


The 2nd parameter of the forEach callback function is the index of the current value.

let list = [1, 2, 3, 4, 5];

list.forEach((value, index) => {
  if (index == list.length - 1) {
    console.log(value);
  }
})
like image 29
toskv Avatar answered Sep 20 '22 13:09

toskv