私はテーブルを持っています:
<table>
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
</table>
各行がどこに来るかを示す配列[{index: 2},{index: 1},{index: 0}]
(最初の行は配列の最後、2 番目の行は1
配列内、3 番目の行0
は配列内)。
私はテーブルを持っています:
<table>
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
</table>
各行がどこに来るかを示す配列[{index: 2},{index: 1},{index: 0}]
(最初の行は配列の最後、2 番目の行は1
配列内、3 番目の行0
は配列内)。
これが私のアプローチです。
// create a new temporary tbody outside the DOM (similar to jQuery's detach)
var tbody_tmp = document.createElement('tbody');
// itterate through the array in the order of a new table
for(var i = 0, j = data.length; i < j; i++)
{
// make a copy of current row (otherwise, append child removes the row from the rows array and messes up the index-finder; there got be a better way for this)
var row = rows[data[i].index].cloneNode(true);
tbody_tmp.appendChild(row);
// reset the index to reflect the new table order (optional, outside the sample)
data[i].index = i;
}
// Note that tbody is a jquery object
tbody.parent()[0].replaceChild(tbody_tmp, tbody[0]);
ただし、クローン作成のアプローチは遅いです。10,000 件以上のレコードがある場合、約 1200 ミリ秒かかります。さらに、jQuery を使用しないアプローチが推奨されます。
他の誰かが必要に応じて十分に単純だと思う場合に備えて、これを投稿します (1,000 行未満)。
何時間もの落ち着きのない思考の後、私は次のことになりました。このサンプルでは不十分な場合は、その背後にあるロジックを説明するブログ投稿全体を書きましたhttp://anuary.com/57/sorting-large-tables-with-javascript。
// Will use this to re-attach the tbody object.
var table = tbody.parent();
// Detach the tbody to prevent unnecessary overhead related
// to the browser environment.
var tbody = tbody.detach();
// Convert NodeList into an array.
rows = Array.prototype.slice.call(rows, 0);
var last_row = rows[data[data.length-1].index];
// Knowing the last element in the table, move all the elements behind it
// in the order they appear in the data map
for(var i = 0, j = data.length-1; i < j; i++)
{
tbody[0].insertBefore(rows[data[i].index], last_row);
// Restore the index.
data[i].index = i;
}
// Restore the index.
data[data.length-1].index = data.length-1;
table.append(tbody);