1

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?

Community
  • 1
  • 1
Kandianne Pierre
  • 314
  • 1
  • 5
  • 17
  • It would be much easier to answer if you'd show us your code. Please take a look at [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) – uzilan Aug 05 '16 at 12:21

2 Answers2

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