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

Viewed 19861

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.

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);
    }
});

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);
  }
})
Related