Skip to content

JavaScript: Opposite Arrays

Manipulating information is core to any programming language. JavaScript is not any exception, particularly as JSON has token over as a primary information supply structure. One such information manipulation is reversing arrays. You could wish to opposite an array to turn most up-to-date transactions, or easy alphabetic sorting.

Reversing arrays with JavaScript initially was once carried out by the use of opposite however that might mutate the unique array:

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

// Opposite it with out reassigning:

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

Enhancing the unique array is a legacy method. To keep away from this mutation, we would replica the array after which opposite it:

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

Nowadays we will use toReversed to keep away from mutating the unique array:

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

Fending off mutation of information items is amazingly vital in a programming language like JavaScript the place object references are significant.

  • Chris Coyier’s Favorite CodePen Demos

    David requested me if I would be up for a visitor publish selecting out a few of my favourite Pens from CodePen. A frightening activity! There are such a large amount of! I controlled to select a couple of although that experience blown me away during the last few months. When you…

  • An Interview with Eric Meyer

    Your early CSS books had been instrumental in pushing my love for entrance finish applied sciences. What was once it about CSS that you just fell in love with and drove you to write down about it? To start with blush, it was once the simplicity of it as in comparison to the table-and-spacer…