Public
Edited
Oct 12, 2022
1 fork
Importers
3 stars
Insert cell
Insert cell
function sorterSelect(data) {
if (!data || !data.length) {
return html`Please provide valid data as an array`;
}
const columns = Object.keys(data[0]);

const select = multiAutoSelect({
options: columns,
nestedselection: (d, button, ele, fm) => {
// Initialize the sort order
if (!fm.order) {
fm.order = [];
}
// Options to select
let options = ["⬆️", "⬇️"];

//Get order when there is a change in order or selection
function getOrder() {
fm.order = [];
for (let child of fm[1].childNodes) {
fm.order.push(child.childNodes[1]?.nodeValue);
}
}

// Update the order if the elements are re-ordered
fm.output.addEventListener("update", () => getOrder());

ele.addEventListener("click", () => {
// Initialize the nested option only when the length is 2
if (ele.childNodes.length === 2) {
//Get random option
let randoption = options[Math.floor(Math.random() * options.length)];
//Insert before the delete button
ele.insertBefore(html`${randoption}`, button);
fm.order.push(randoption);
fm.dispatchEvent(new Event("input", { bubbles: true }));

return;
}
// Get the new option
let newoption =
(options.indexOf(ele.childNodes[1]?.nodeValue) + 1) % options.length;
ele.removeChild(ele.childNodes[1]);
ele.insertBefore(html`${options[newoption]}`, button);
fm.dispatchEvent(new Event("input", { bubbles: true }));
getOrder();
});
// For the 1st time initialization
ele.click();
}
});

const control = html`<form>
<div><label>Sort by: ${select}</label></div>
</form>`;

control.value = (a, b) =>
select.value.reduce((prevGroupBy, currGroupBy, index) => {
return (
prevGroupBy ||
(select.order[index] === "⬇️"
? d3.descending(a[currGroupBy], b[currGroupBy])
: d3.ascending(a[currGroupBy], b[currGroupBy]))
);
}, false);

return control;
}
Insert cell
viewof sortBy = sorterSelect(data)
Insert cell
data.sort(sortBy)
Insert cell
data = FileAttachment("cars.json").json()
Insert cell
objects = [
{ id: 1, name: "John" },
{ id: 2, name: "Alexis" },
{ id: 3, name: "Guerra" },
{ id: 4, name: "Gomez" }
]
Insert cell
viewof eg2 = multiAutoSelect({ options: objects, attr: (d) => d.name })
Insert cell
import { multiAutoSelect } from "a7aa70dc3a134c46"
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more