🎃

文字列比較のPythonとJavaScriptの違い

2025/01/31に公開

PythonJavaScript で末尾の文字を基準に並び替える時、Python では sortedkey に文字列を渡せばいいが、JavaScriptsort では そのままだと文字列比較ではなく数値比較にしか使えないので少し工夫が必要である。

Python

def sort_by_last_char(arr):
    return sorted(arr, key=lambda x: x[-1])

arr = ['apple', 'banana', 'cherry', 'date']
sorted_arr = sort_by_last_char(arr)
print(sorted_arr)
  • sorted 関数は、指定されたキー (key) に基づいて配列を並び替えます。
  • ここでは、key=lambda x: x[-1] としており、各文字列の末尾の文字を基準に並び替えを行います

JavaScript

localeCompareを使う方法

const sortByLastCharLocaleCompare = arr => arr.sort((a, b) => a.charAt(a.length - 1).localeCompare(b.charAt(b.length - 1))); //sliceを用いても可能

const arr1 = ['apple', 'banana', 'cherry', 'date'];
const sortedArr1 = sortByLastCharLocaleCompare(arr1);
console.log(sortedArr1);
  • sort メソッドは、配列を指定された比較関数に基づいて並び替えます。
  • localeCompare は、文字列をローカル設定に基づいて比較し、並び替えを行います。

charCodeAtを使う方法

const sortByLastCharCharCodeAt = arr => arr.sort((a, b) => a.charCodeAt(a.length - 1) - b.charCodeAt(b.length - 1));

const arr2 = ['apple', 'banana', 'cherry', 'date'];
const sortedArr2 = sortByLastCharCharCodeAt(arr2);
console.log(sortedArr2);
  • charCodeAt メソッドは、指定した位置にある文字のUnicodeを返します。
  • sort メソッド内で、文字のUnicode値に基づいて並び替えを行っています

Discussion