JavaScript配列sort()
例
配列の並べ替え:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
並べ替えてから順序を逆にします。
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
定義と使用法
配列のsort()
要素を並べ替えます。
元のsort()
配列を上書きします。
はsort()
、要素を文字列としてアルファベット順および昇順で並べ替えます。
関連項目:
ソート比較機能
文字列のアルファベット順の並べ替えはうまく機能します(「Apple」は「Banana」の前にあります)。
ただし、数値を並べ替えると、誤った結果が生成される可能性があります。
「2」は「1」よりも大きいため、「25」は「100」よりも大きくなります。
これは、「比較機能」を提供することで修正できます(以下の例を参照)。
構文
array.sort(compareFunction)
パラメーター
Parameter | Description |
compareFunction |
Optional. A function that defines a sort order. The function should return a negative, zero, or positive value, depending on the arguments:
When sort() compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value. Example: The sort function will sort 40 as a value lower than 100. When comparing 40 and 100, sort() calls the function(40,100). The function calculates 40-100, and returns -60 (a negative value). |
戻り値
アイテムがソートされた配列。 |
その他の例
番号を昇順で並べ替えます。
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
番号を降順で並べ替えます。
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
最小値を見つけます:
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in ascending order
points.sort(function(a, b){return a-b});
let lowest = points[0];
最高値を見つける:
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in descending order:
points.sort(function(a, b){return b-a});
let lowest = points[0];
最高値を見つける:
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in ascending order:
points.sort(function(a, b){return a-b});
let highest = points[points.length-1];
ブラウザのサポート
sort()
ECMAScript1(ES1)機能です。
ES1(JavaScript 1997)は、すべてのブラウザーで完全にサポートされています。
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |