My question is how to do the sorting of the data in an HTML/D3 code shown below. I code in Python, and HTML/CSS are new to me. I have the following code, I am preparing the data inside, how can I sort this data. Without considering the and not taking care of the labels. I want to just sort the data. How can I accomplish the same. Many thanks. I am learning this.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3: Sorting visual elements</title>
<script src="//d3js.org/d3.v5.min.js" charset="utf-8"></script>
</head>
<body>
<script type="text/javascript">
//Width and height
var w = 600;
var h = 250;
var dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];
var xScale = d3.scaleBand()
.domain(d3.range(dataset.length))
.rangeRound([0, w])
.paddingInner(0.05);
var yScale = d3.scaleLinear()
.domain([0, d3.max(dataset)])
.range([0, h]);
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
//Create bars
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", (d,i) => xScale(i) )
.attr("y", d => h - yScale(d) )
.attr("width", xScale.bandwidth())
.attr("height", d => yScale(d) )
.attr("fill", d => "rgb(0, 0, " + (d * 10) + ")" )
.on("mouseover", function() {
d3.select(this)
.attr("fill", "orange");
})
.on("mouseout", function(d) {
d3.select(this)
.transition()
.duration(250)
.attr("fill", "rgb(0, 0, " + (d * 10) + ")")
})
.on("click", () => sortBars() );
//Create labels
svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(d => d)
.attr("text-anchor", "middle")
.attr("x", (d, i) => xScale(i) + xScale.bandwidth() / 2)
.attr("y", d => h - yScale(d) + 14 )
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");
//Define sort function
var sortBars = function() {
svg.selectAll("rect")
.sort((a, b) => d3.ascending(a, b) )
.transition()
.duration(1000)
.attr("x", (d, i) => xScale(i) );
};
</script>
</body>
</html>