2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】配列逆順操作メソッド reverse() vs toReversed()

Posted at

はじめに

JavaScript で配列の要素を逆順に並び替える方法として、 reverse() とES2023で導入された toReversed() があります。これらは似たような機能を提供しますが、重要な違いがあります。
この記事では、それぞれのメソッドの概要やサンプルコードを通して、これらの違いと使い分けについて解説します。

reverse() 元の配列を直接変更する

reverse() は配列の要素を元の配列上で逆順に並び替えます。
メモリ効率がよいですが、元の配列の順序が変わってしまう点に注意が必要です。

sample.ts
const array = [1, 2, 3];
console.log(array);
// Output: Array [1, 2, 3]

const reversed = array.reverse();
console.log(reversed);
// Output: Array [3, 2, 1]

console.log(array);
// Output: Array [3, 2, 1]

reverse() 実行後、実行後の値を受け取った配列だけでなく、元の配列も並び替えられています。

toReversed() 元の配列を変更せずに新しい配列を作成する

toReversed() は配列の要素を逆順に並び替えた新しい配列を返します。元の配列は変更されません。ES2023 で導入された比較的新しいメソッドです。
元の配列を保持する必要がある場合や不変性を重視する場合に適しています。一方、新しい配列を作成するため、非常に大きな配列を扱う場合、パフォーマンスへの影響に注意する必要があります。

sample.ts
const array = [1, 2, 3];
console.log(array);
// Output: Array [1, 2, 3]

const reversed = array.toReversed();
console.log(reversed);
// Output: Array [3, 2, 1]

console.log(array);
// Output: Array [1, 2, 3]

reverse() 実行後、実行後の値を受け取った配列は並び替えられています。一方、元の配列の順序は変わっていません。

まとめ

reverse()toReversed() の主な違いは、元の配列の変更有無です。

  • reverse(): 元の配列を直接変更する
  • toReversed(): 元の配列を変更せずに、新しい配列を返す

参考

2
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?