Last active
November 7, 2019 14:56
-
-
Save digiguru/039a3a6287185cad085b040ff7d258c7 to your computer and use it in GitHub Desktop.
Get a table of links, sort them and output to a table of links.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Takes an HTML table from a page that may be layed out as follows: | |
// | Zoe | Brenda | | | |
// | Adam | Arthur | Bob | | |
// | Joe | Zoe | | |
// and lays them out like this | |
// | Adam | Arthur | Brenda | | |
// | Bob | Joe | Zoe | | |
// | |
var templates = { | |
table: (data) => `<table class="ms-rteTable-default" width="100%" cellspacing="0">${data}</table>`, | |
row: (data) => `<tr class="ms-rteTableEvenRow-default">${data}</tr>`, | |
cell: (link, name) => `<td class="ms-rteTableEvenCol-default" rowspan="1" colspan="1" style="width:16.66%;"><h2><a href="${link}">${name}</a></td>` | |
} | |
function findData (query) { | |
var a = | |
// Get the items from the page, and turn it into a list | |
[... document.querySelectorAll(query)] | |
// pulling the metadata out that we want | |
.map((e) => { | |
return {t: e.innerText.trim().replace("",""), h: e.href} | |
}) | |
// remove nulls | |
.filter(e => e.t); | |
//remove duplicates | |
a = [...new Set(a)]; | |
//sort by text element | |
a.sort(sortByName); | |
return a; | |
} | |
function sortByName(one, two) { | |
var nameA = one.t.toUpperCase(); // ignore upper and lowercase | |
var nameB = two.t.toUpperCase(); // ignore upper and lowercase | |
if (nameA < nameB) { | |
return -1; | |
} | |
if (nameA > nameB) { | |
return 1; | |
} | |
// names must be equal | |
return 0; | |
} | |
function rowBuilder(arr, columns) { | |
var rows = []; | |
var row = []; | |
var addRow = function() { | |
rows.push(templates.row(row.join(""))); | |
row = []; | |
} | |
arr.forEach((e, i) => { | |
row.push(templates.cell(e.h, e.t)); | |
if (i % columns === columns-1) { | |
addRow(); | |
} | |
}); | |
if (row.length) { | |
addRow(); | |
} | |
return rows.join(""); | |
} | |
function tableBuilder(arr, columns) { | |
var data = rowBuilder(arr, columns); | |
return templates.table(data); | |
} | |
//example usage | |
console.log(tableBuilder(findData("table.ms-rteTable-default td a"), 6)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment