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?

2
  • You want to empty the array then? Commented Dec 6, 2016 at 19:40
  • Also, both _.remove and _.pullAt aren't in underscore. Are you using lodash? Commented Dec 6, 2016 at 19:52

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.