雑記帳

整理しない情報集

テーブルのセル結合を正規化するJavascript

公開日:

カテゴリ: Javascript

テーブルのセル結合をテキストとして抽出して2次元配列に正規化するスクリプトのメモ書きです。

仕様

  • テーブルを2次元配列として返却 ([行][列])
  • 配列の値はセルの textContent の内容
  • colspanrowspan で結合された部分は左上のセルに内容、それ以外の結合先には NULL を出力(メイン機能)
  • 行・列の数が合わない分は NULL で埋める

ソースコード

const normalizeTable = t => {
	const table = t.cloneNode(true);
	const output = [];

	[...table.getElementsByTagName("tr")].forEach((x, i) => {
		[...x.children].forEach((y, j) => {
			if (Array.isArray(output[i]) && (output[i][j] || output[i][j]===null)) {
				while (output[i][j] || output[i][j] === null) {
					j++;
				}
			}
			for (let p = 0; p < y.rowSpan; p++) {
				if (!output[i + p] ) output[i + p] = [];
				for (let q = 0; q < y.colSpan; q++) {
					output[i + p][j + q] = (p === 0 && q === 0) ? y.textContent : null;
				}
			}
		});
	});

	const c = Math.max(...output.map(a => a.length));
	output.forEach(a => a.length < c ? a.length = c : 0);
	output.map(a => [...a].map(b => b !== undefined ? b : null));
	return output;
};

minify

const normalizeTable=z=>{const t=z.cloneNode(1),o=[];[...t.getElementsByTagName("table")].forEach(a=>a.parentNode.removeChild());[...t.getElementsByTagName("tr")].forEach((x,i)=>[...x.children].forEach((y,j)=>{if(Array.isArray(o[i])&&(o[i][j]||o[i][j]===null))while(o[i][j]||o[i][j]===null)j++;for(let p=0;p<y.rowSpan;p++){if(!o[i+p])o[i+p]=[];for(let q=0;q<y.colSpan;q++)o[i+p][j+q]=(p===0&&q===0)?y.textContent:null}}));const c=Math.max(...o.map(a=>a.length));o.forEach(a=>a.length<c?a.length=c:0);return o.map(a=>[...a].map(b=>b!==undefined?b:null))};

サンプル

テーブル

11131416
212227
31323435
4143444546

実行結果

[
	["11", NULL, "13", "14", NULL, "16", NULL],
	["21", "22", NULL, NULL, NULL, NULL, "27"],
	["31", "32", NULL, "34", "35", NULL, NULL],
	["41", NULL, "43", "44", "45", "46", NULL]
]

カテゴリ: Javascript