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.
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.
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.
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.
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).
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);
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With