Skip to content

Instantly share code, notes, and snippets.

@digiguru
Last active November 7, 2019 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digiguru/039a3a6287185cad085b040ff7d258c7 to your computer and use it in GitHub Desktop.
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.
// 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