LoginSignup
0
0

More than 1 year has passed since last update.

JavaScriptで数値をsort()する時の注意

Last updated at Posted at 2021-02-22

配列の数値を昇順で表示したい(小さい順)

Paziaで問題を解いていて「あれっ?」ってなったので記録。
ある配列

const arr = ['4','6','3','-10','21','0']
// 配列の中身を「文字列」→「数字」
const num = arr.map(Number)
console.log(num) 
// [4,6,3,-10,21,0 ]

があるとする。
これを昇順で表示しようとした際に、以下のようにして失敗。

const newNum = num.sort()
console.log(newNum)
// (6) [-10, 0, 21, 3, 4, 6]

このようになってしまうのは、数値は文字列へ変換され、Unicode順になるので小さい順にならないそうです。
よって比較関数を利用します。

const newNum = num.sort((a,b) => a - b);
console.log(newNum)
// (6) [-10, 0, 3, 4, 6, 21]

このようにすると昇順になります。

0
0
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
0
0