JavaScript: Reverse Arrays

By  on  

Manipulating data is core to any programming language. JavaScript is no exception, especially as JSON has token over as a prime data delivery format. One such data manipulation is reversing arrays. You may want to reverse an array to show most recent transactions, or simple alphabetic sorting.

Reversing arrays with JavaScript originally was done via reverse but that would mutate the original array:

// First value:
const arr = ['hi', 'low', 'ahhh'];

// Reverse it without reassigning:
arr.reverse();

// Value:
arr (3) ['ahhh', 'low', 'hi']

Modifying the original array is a legacy methodology. To avoid this mutation, we'd copy the array and then reverse it:

const reversed = [...arr].reverse();

These days we can use toReversed to avoid mutating the original array:

const arr = ['hi', 'low', 'ahhh'];
const reversed = arr.toReversed(); // (3) ['ahhh', 'low', 'hi'];
arr; // ['hi', 'low', 'ahhh']

Avoiding mutation of data objects is incredibly important in a programming language like JavaScript where object references are meaningful.

Recent Features

Incredible Demos

  • By
    Create a Simple News Scroller Using MooTools, Part I:  The Basics

    News scroller have been around forever on the internet. Why? Because they're usually classy and effective. Over the next few weeks, we'll be taking a simple scroller and making it into a flexible, portable class. We have to crawl before we...

  • By
    Image Reflection with jQuery and MooTools

    One subtle detail that can make a big difference on any web design is the use of image reflections. Using them too often can become obnoxious but using reflections on large, "masthead" images is a classy enhancement. Unfortunately creating image reflections within your...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!