Execute function for each array element in reverse

OSCC · JavaScript, Array · Oct 19, 2020

Executes a provided function once for each array element, starting from the array's last element.

const forEachRight = (arr, callback) =>
  arr
    .slice()
    .reverse()
    .forEach(callback);
forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1'

Recommended snippets

  • Mapped array union

    JavaScript, Array

    Returns every element that exists in any of the two arrays at least once, after applying the provided function to each array element of both.

  • Finds all unique values of an array, based on a provided comparator function, starting from the right.

  • Partition array in two

    JavaScript, Array

    Groups the elements into two arrays, depending on the provided function's truthiness for each element.