Skip to content

Instantly share code, notes, and snippets.

@xialvjun

xialvjun/tree_table.js

Last active Jan 26, 2018
Embed
What would you like to do?
import React, { Component } from 'react';
import { render } from 'react-dom';
var data = [
['1','1.1','1.1.1'],
['1','1.1','1.1.2'],
['1','1.1','1.1.3'],
['1','1.2','1.2.1'],
['1','1.2','1.2.2'],
['2','2.1','2.1.1', '2.1.1.1'],
['2','2.1','2.1.1', '2.1.1.2'],
['2','2.2','2.2.1', '2.2.1.1'],
['2','2.2','2.2.2'],
]
// data.sort()
const max_col = data.reduce((acc, cv) => Math.max(acc, cv.length), 0);
const rendered = new Array(max_col).fill(0).map(_ => []);
var tb = <table border="2">
{data.map((row, row_idx) => {
const filtered_row = row.filter((d, col_idx) => rendered[col_idx].indexOf(d)===-1);
const to_add_length = row.length - filtered_row.length;
return <tr key={row.join('|')}>{filtered_row.map((d, col_idx) => {
const true_col_idx = to_add_length + col_idx;
rendered[true_col_idx].push(d);
return <td key={d} rowSpan={data.filter(r => r[true_col_idx]===d).length} colSpan={row[true_col_idx+1] ? 1 : max_col - true_col_idx}>{d}</td>
})}</tr>
})}
</table>
console.log(rendered);
render(tb, document.getElementById('root'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment