ソートは「第11回 sorter で 日付をソートする」 を記述しましたが、少しわかりにくかったので簡単な例を記述します。
任意の文字列をソートするにはソートしたい文字列の順番を配列で定義します。
サンプルコードでは文字列の順番を以下のように定義しました。
const list = [ "apple", "orange", "banana", "pineapple" ];
ソート処理は indexOf 関数により配列のインデックス番号を取得して、行います。
sorter:function(a,b){
// a、b-比較される2つの値
return list.indexOf(a)-list.indexOf(b)
}
アロー関数を用いると return を省略できるので 一行で書くことができます。
sorter:(a,b)=>list.indexOf(a)-list.indexOf(b)
以下、カラム定義、データ定義、実行結果、サンプルコードです。
カラム定義
{
title:"item",
field:"item",
sorter:(a,b)=>list.indexOf(a)-list.indexOf(b)
}
データ定義
data: [
{ item: "banana" },
{ item: "apple" },
{ item: "orange" },
{ item: "pineapple" }
],
実行結果
サンプルコード
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<link href="https://unpkg.com/tabulator-tables@4.6.3/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables@4.6.3/dist/js/tabulator.min.js"></script>
</head>
<body onload="show_table()">
<h1 id=title> 任意の文字列をソートする </h1>
<div id="table"></div>
<script type="text/javascript">
const list = [ "apple", "orange", "banana", "pineapple" ];
const show_table=function(){
new Tabulator("#table", {
data: [
{ item: "banana" },
{ item: "apple" },
{ item: "orange" },
{ item: "pineapple" }
],
columns: [
{
title:"item",
field:"item",
sorter:(a,b)=>list.indexOf(a)-list.indexOf(b)
}
]
});
}
</script>