HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Iterate over a JavaScript array from right to left

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptleftfromiteraterightoverarray

Problem

Array.prototype.forEach() is pretty convenient, but what if you want to iterate over an array from right to left? Using a for loop is an option, but there are more elegant tools at our disposal.
@Quick refresher
Reversing an array can be easily accomplished using Array.prototype.reverse(), but it mutates the original array. In order to avoid that, we have to create a shallow clone, using Array.prototype.slice(). This needs to be done prior to reversing to avoid the original array being mutated. Finally, we can use Array.prototype.forEach() to iterate over the reversed array.

Solution

const forEachRight = (arr, callback) =>
  arr.slice().reverse().forEach(callback);

forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1'


Reversing an array can be easily accomplished using Array.prototype.reverse(), but it mutates the original array. In order to avoid that, we have to create a shallow clone, using Array.prototype.slice(). This needs to be done prior to reversing to avoid the original array being mutated. Finally, we can use Array.prototype.forEach() to iterate over the reversed array.

Code Snippets

const forEachRight = (arr, callback) =>
  arr.slice().reverse().forEach(callback);

forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1'

Context

From 30-seconds-of-code: for-each-right

Revisions (0)

No revisions yet.