[JavaScript] Reversing Array Elements! Behavior and Cautions of the reverse Method

目次

Overview

When you need to sort a timeline from newest to oldest or display a ranking from the bottom up, you must flip the order of an array. In JavaScript, you can reverse the elements of an array in a single line using the reverse method. However, this method has a critical characteristic: it modifies the original array directly. This is called a “destructive change,” and you must handle it carefully.

Specifications (Input/Output)

reverse Method

MethodMeaningReturn Value
array.reverse()Reverses the order of elements “in-place.”The reversed array itself (a reference to the original).
  • Input: None.
  • Output: The array with its order reversed (the same object as the original).
  • Side Effect: The content of the original array is modified.

Basic Usage

Reversing an Array

When you execute this method, the content of the array that the variable points to is rewritten.

const numbers = [1, 2, 3, 4, 5];

// Execution
numbers.reverse();

console.log(numbers); 
// Output: [5, 4, 3, 2, 1]
// Note: The "numbers" variable itself has changed.

Full Code (HTML / JavaScript)

This is an interview order management system. It provides a function to toggle between the default “Arrival Order” and the “Reversed Order” with a single button click.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Interview Order Manager</title>
    <style>
        .list-container {
            font-family: "Segoe UI", sans-serif;
            max-width: 400px;
            padding: 20px;
            border: 2px solid #333;
            border-radius: 8px;
            background-color: #fff;
        }
        h3 { margin-top: 0; text-align: center; }
        .member-list {
            list-style: decimal;
            padding-left: 1.5em;
            margin-bottom: 20px;
            border-top: 1px solid #ccc;
            padding-top: 10px;
        }
        .member-item {
            padding: 5px 0;
            font-size: 1.1rem;
            border-bottom: 1px dashed #eee;
        }
        .btn-reverse {
            width: 100%;
            padding: 10px;
            background-color: #e67e22;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: bold;
            font-size: 1rem;
        }
        .btn-reverse:hover { background-color: #d35400; }
    </style>
</head>
<body>

<div class="list-container">
    <h3>Interview Order List</h3>
    <ol id="interview-list" class="member-list">
        </ol>
    <button id="btn-toggle-order" class="btn-reverse">Switch Order (reverse)</button>
</div>

<script src="order_manager.js"></script>
</body>
</html>

JavaScript

/**
 * Interview Order Management Script
 * Implementation of sorting using the reverse method
 */

// 1. Interviewee List
const interviewees = [
    'Mori',
    'Komori',
    'Nakamori',
    'Omori',
    'Hayashi',
    'Kobayashi',
    'Nakabayashi',
    'Obayashi'
];

const listElement = document.getElementById('interview-list');
const toggleButton = document.getElementById('btn-toggle-order');

/**
 * Function to render the list on the screen
 */
const renderList = () => {
    // Clear the list
    listElement.innerHTML = '';

    interviewees.forEach((name) => {
        const li = document.createElement('li');
        li.className = 'member-item';
        li.textContent = `${name}`;
        listElement.appendChild(li);
    });
};

/**
 * Function to reverse the order
 */
const reverseOrder = () => {
    // Use the reverse method
    // The content of the interviewees array is rewritten in reverse order
    interviewees.reverse();

    // Re-render
    renderList();
};

// Initial display
renderList();

// Event listener
toggleButton.addEventListener('click', reverseOrder);

Custom Points

If you want to sort alphabetically and then reverse the order, you should use sort() before reverse(), like array.sort().reverse(). To make the transition smoother, you can combine this with animation libraries to show elements moving to their new positions instead of simply recreating the list.

Important Notes

The most important thing to remember is that reverse is a destructive method. It changes the original array directly, so you cannot use it if you need to keep the original order. Additionally, the return value is not a new array but a reference to the modified original array. If you set const b = a.reverse(), both a and b will point to the same array, and changing b will also change a.

Advanced Usage

Reversing Without Modifying the Original (toReversed / Spread Syntax)

If you want to keep the original data and only get a reversed version for display, use the following methods.

1. toReversed() Method (Recommended for ES2023+)

Modern JavaScript provides a non-destructive reverse method.

const original = ['Ki', 'Kogi', 'Oki'];
const reversed = original.toReversed();

console.log(original); // ['Ki', 'Kogi', 'Oki'] (Remains the same!)
console.log(reversed); // ['Oki', 'Kogi', 'Ki'] (A new array)

2. Spread Syntax (Traditional Method)

You can copy the array first and then reverse it.

const original = ['Ki', 'Kogi', 'Oki'];
const reversed = [...original].reverse();

Summary

The reverse method is the simplest way to flip an array, but you must account for its side effects because it modifies the original data. You should use reverse() when you want to flip the state of the data itself. If you need to keep the original data while obtaining a reversed result, use toReversed() or the spread syntax. Understanding this difference is essential for managing data states and preventing bugs in your JavaScript applications.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次