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

  • By
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

  • By
    CSS Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome...

Incredible Demos

  • By
    Create a Dojo Lightbox with dojox.image.Lightbox

    One of the reasons I love the Dojo Toolkit is that it seems to have everything.  No scouring for a plugin from this site and then another plugin from that site to build my application.  Buried within the expansive dojox namespace of Dojo is

  • By
    Sexy Opacity Animation with MooTools or jQuery

    A big part of the sexiness that is Apple software is Apple's use of opacity. Like seemingly every other Apple user interface technique, it needs to be ported to the web (</fanboy>). I've put together an example of a sexy opacity animation technique...

Discussion

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