JavaScript: Reverse Arrays

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 […]

The post JavaScript: Reverse Arrays appeared first on David Walsh Blog.

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.

The post JavaScript: Reverse Arrays appeared first on David Walsh Blog.

Recommended Story For You :

GET YOUR VINCHECKUP REPORT

The Future Of Marketing Is Here

Images Aren’t Good Enough For Your Audience Today!

Last copies left! Hurry up!

GET THIS WORLD CLASS FOREX SYSTEM WITH AMAZING 40+ RECOVERY FACTOR

Browse FREE CALENDARS AND PLANNERS

Creates Beautiful & Amazing Graphics In MINUTES

Uninstall any Unwanted Program out of the Box

Did you know that you can try our Forex Robots for free?

Stop Paying For Advertising And Start Selling It!

By Robert Metras

Rob is an experienced internet marketer and author. He helps businesses, professionals and organizations to raise their online visibility in local search and get more from their promotions and advertising and free use of search engine products.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.