JavaScriptのソート(つづき)

前回のソートのはなしの続きです。

総合開発環境(IntelliJ等)でlist.sort()の「sort() 」の部分をCommand+クリックしていただくと、この関数のソートにピューンと飛んでいきます。

すると、下記のようなコメントとソースコードの記述にたどりつきます。

/**
* Sorts an array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if first argument is less than second argument, zero if they're equal and a positive
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
* ```ts
* [11,2,22,1].sort((a, b) => a - b)
* ```
*/
sort(compareFn?: (a: T, b: T) => number): this;

ということですので、下記のようにComparator のような関数を引数に渡すと期待値通りの結果となります。


export {}
const comp = (a: number , b: number):number => {
   if ( a > b ) {
       return 1;
   } else if (a === b) {
       return 0;
   } else {
       return -1;
   }
};
const list =[1,2,4,6,3,2,88,9];
console.log(list.sort(comp));
{
   let list_number: number[];
   list_number = [1, 2, 4, 6, 3, 2, 88, 9];
   console.log(list_number.sort(comp));
};

実行結果は下記のようにちゃーんとソートされたものになりますね。

$ ts-node test.ts
[
1, 2, 2, 3,
4, 6, 9, 88
]
[
1, 2, 2, 3,
4, 6, 9, 88
]

じゃあね。

この記事が気に入ったらサポートをしてみませんか?