0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

配列を並べ替える

Posted at

JavaScriptで配列を並び替える方法のメモ。
数値、アルファベットの場合はsortを使用します。

const array = ['Delta', 'Bravo', 'Alfa', 'Charlie', 'Echo']
console.log(array.sort()) // ['Alfa', 'Bravo', 'Charlie', 'Delta', 'Echo']

降順の場合、

const array = ['Delta', 'Bravo', 'Alfa', 'Charlie', 'Echo']
array.sort((a, b) => {
  if (a > b)
    return -1
  if (b > a)
    return 1
}) // ['Echo', 'Delta', 'Charlie', 'Bravo', 'Alfa']

数値の配列でも同じようにソートできます。
日本語の場合はlocaleCompareを使用します。

const array = ["うし", "わに", "あひる", "みかん", "よっと", "いぬ", "かばん"]

// 昇順
array.sort((a, b) => a.localeCompare(b, 'ja'))
// 降順
array.sort((a, b) => b.localeCompare(a, 'ja'))

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?