【超入門】JavaScriptのsort()メソッドで文字列を並べ替えてみよう!
JavaScriptで文字列をソートする方法
sort() メソッドを使う
基本的な使い方
const strings = ["abc", "def", "ghi"];
strings.sort(); // ["abc", "def", "ghi"]
// 降順に並べ替える
strings.sort((a, b) => b.localeCompare(a)); // ["ghi", "def", "abc"]
オプションの指定
localeCompare
メソッド:ロケールに基づいた比較を行うcompareFunction
オプション:比較関数を指定
例:日本語を50音順に並べ替える
const strings = ["あいうえお", "かきくけこ", "さしすせそ"];
strings.sort((a, b) => a.localeCompare(b, "ja")); // ["あいうえお", "かきくけこ", "さしすせそ"]
配列の要素を直接比較する
const strings = ["abc", "def", "ghi"];
const sortedStrings = [];
for (let i = 0; i < strings.length; i++) {
for (let j = i + 1; j < strings.length; j++) {
if (strings[i] > strings[j]) {
const temp = strings[i];
strings[i] = strings[j];
strings[j] = temp;
}
}
sortedStrings.push(strings[i]);
}
console.log(sortedStrings); // ["abc", "def", "ghi"]
ライブラリを使う
Lodashなどのライブラリを使うと、より簡単にソートできます。
import _ from "lodash";
const strings = ["abc", "def", "ghi"];
const sortedStrings = _.sortBy(strings); // ["abc", "def", "ghi"]
// 降順に並べ替える
const sortedStrings = _.sortBy(strings, (str) => -str.length); // ["ghi", "def", "abc"]
sort() メソッドを使う
const strings = ["abc", "def", "ghi"];
strings.sort();
console.log(strings); // ["abc", "def", "ghi"]
降順に並べ替える
const strings = ["abc", "def", "ghi"];
strings.sort((a, b) => b.localeCompare(a));
console.log(strings); // ["ghi", "def", "abc"]
const strings = ["あいうえお", "かきくけこ", "さしすせそ"];
strings.sort((a, b) => a.localeCompare(b, "ja"));
console.log(strings); // ["あいうえお", "かきくけこ", "さしすせそ"]
配列の要素を直接比較する
const strings = ["abc", "def", "ghi"];
const sortedStrings = [];
for (let i = 0; i < strings.length; i++) {
for (let j = i + 1; j < strings.length; j++) {
if (strings[i] > strings[j]) {
const temp = strings[i];
strings[i] = strings[j];
strings[j] = temp;
}
}
sortedStrings.push(strings[i]);
}
console.log(sortedStrings); // ["abc", "def", "ghi"]
ライブラリを使う
import _ from "lodash";
const strings = ["abc", "def", "ghi"];
const sortedStrings = _.sortBy(strings);
console.log(sortedStrings); // ["abc", "def", "ghi"]
// 降順に並べ替える
const sortedStrings = _.sortBy(strings, (str) => -str.length);
console.log(sortedStrings); // ["ghi", "def", "abc"]
JavaScriptで文字列をソートする他の方法
Array.prototype.reduce メソッドを使う
const strings = ["abc", "def", "ghi"];
const sortedStrings = strings.reduce((acc, str) => {
acc.push(str);
acc.sort();
return acc;
}, []);
console.log(sortedStrings); // ["abc", "def", "ghi"]
Array.prototype.filter メソッドを使う
const strings = ["abc", "def", "ghi"];
const sortedStrings = strings.filter((str, i) => strings.slice(i + 1).every((s) => str <= s));
console.log(sortedStrings); // ["abc", "def", "ghi"]
これらの方法は、上記で紹介した方法よりも複雑ですが、より柔軟なソート処理を行うことができます。
特殊な文字列のソート
- 全角文字と半角文字を混在させる場合
- 日本語を五十音順に並べ替えたい場合
これらの場合は、localeCompare
メソッドや、ライブラリの sortBy
メソッドなど、ロケール情報を考慮したソート方法を使う必要があります。
JavaScriptで文字列をソートするには、さまざまな方法があります。
- 簡単なソートには
sort
メソッド - 複雑なソートにはソートアルゴリズムの実装
- 特殊な文字列には
localeCompare
メソッド
それぞれの特徴を理解して、目的に合った方法を選びましょう。
javascript string