33
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[JS]破壊的ではないsortのやり方

Posted at

JavaScriptのsortは破壊的。
それを防ぐには以下のようにしてsortを実行する。

// 壊れちゃう!
var arr = [3,5,1,7,2],
    arr2 = arr.sort(); // => arrも変更されてarr2と同じになる

// 壊れません
var arr = [3,5,1,7,2],
    arr3 = arr.slice().sort();  // => arrは変更されず、arr3にはソート済みの配列が入る

参考:
http://d.hatena.ne.jp/kitokitoki/20110615/p1

33
21
0

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
33
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?