I'm looping through an array and splicing specific elements out, but my loop breaks after the first iteration because I'm skipping over an index when one is removed. I see here How to iterate over an array and remove elements in JavaScript that you can use an original loop and start from the top of the array and decrement i, but can I do this same thing using lodash?
Asked
Active
Viewed 309 times
2 Answers
1
Instead of using a for-loop, you could just remove elements with lodash's filter
or remove
instead:
var array = [1, 10, 100, 1000];
function isLargerThan10(num) {
return num > 10;
}
// return the filtered array:
var filtered = _.filter(array, isLargerThan10);
console.log(filtered);
// modify the array:
_.remove(array, isLargerThan10);
console.log(array);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.1/lodash.min.js"></script>

Tholle
- 108,070
- 19
- 198
- 189
1
Read about remove, filter and forEachRight methods. You should find the answer.

evilive
- 1,781
- 14
- 20