Is there a way to loop backwards through an array using forEach
(not any other kind of loop, I know how to do with with a for / standard ways) and without actua
No, forEach
only processes forward through the array. So you'd have to do something else, which you've said in your question was out of scope.
I can think of two options which just use precursors to using forEach
(so, they don't use a for
loop or other kind of loop). I don't know if those would be out of scope or not, so here they are:
Copy the array and reverse the copy, then use forEach
on it
Use Object.keys
to get the indexes, reverse that, then use forEach
on it (which will loop through the indexes, not the values, but then we can look them up)
Here's #1:
slice
copies the array (shallow copy, so not likely to be expensive), then we reverse it, then forEach
:
var a = ['one', 'two', 'three'];
a.slice().reverse().forEach(function(entry) {
console.log(entry);
});
console.log("Proof that a is not, itself, reversed: " +
JSON.stringify(a));
Here's #2:
We use Object.keys
to get the array indices (using filter
if you store non-element properties in your arrays), reverse that, and then loop through the result:
var a = ['one', 'two', 'three'];
Object.keys(a).reverse().forEach(function(index) {
console.log(a[index]);
});
console.log("Proof that a is not, itself, reversed: " +
JSON.stringify(a));
Side note: Here's what I mean about using filter
if you have non-element properties on your array:
var a = ['one', 'two', 'three'];
a.nonElementProperty = "foo";
Object.keys(a).filter(function(name) {
return String(+name) === name;
}).reverse().forEach(function(index) {
console.log(a[index]);
});
console.log("Proof that a is not, itself, reversed: " +
JSON.stringify(a));