2

I want to iterate over an array in reverse order using Lodash. Is that possible?

My code looks like below.

var array = [1, 2, 3, 4, 5];
_.each(array, function(i) {
   _.remove(array, i);
});

When I do _.pullAt(array, 0) new array is [2, 3, 4, 5]. All array elements shifted to left by 1 position, and current index is pointing to element 3. After next iteration, 3 will get deleted and then 5. After 3rd iteration array contains [2, 4] which I couldn't delete.

If I iterate over the array in reverse order, then this problem won't arise. In Lodash, can I iterate over an array in reverse order?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Santosh Hegde
  • 3,420
  • 10
  • 35
  • 51

2 Answers2

3

You can use _.reverse available in version 4:

var array = [1, 2, 3, 4, 5];
array = _.reverse(array)
console.log(array)
//5, 4, 3, 2, 1
Darlan Dieterich
  • 2,369
  • 1
  • 27
  • 37
1

See How do I empty an array in JavaScript? if you only want that and choose your weapon.

Otherwise, strictly answering the question, to iterate the indices from the length of the array to zero, you could use the "down-to" --> operator1. But that's not really necessary, even underscore isn't necessary in this case as the .pop function is enough.

var arr = [1, 2, 3, 4, 5],
    index = arr.length;

while (index --> 0) {
    console.log(index);
    arr.pop();
}
console.log(arr);

If you're using Lodash like the functions referenced in the question seem to indicate, you could use _.eachRight.

var arr = [1, 2, 3, 4, 5];

_.eachRight(arr, function(value) {
  console.log(value);
  arr.pop();
});

console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

1 The down-to operator doesn't exist and is only a -- decrement followed by a > comparison.

Community
  • 1
  • 1
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129