Question

Check out my spreadsheet:

http://bl.ocks.org/emeeks/11310634

When you click the 'sort' button, it runs this function:

function sortSheet() {
    var dataset = d3.selectAll("div.datarow").data();
    dataset.sort(function(a,b) {
        var aDate = new Date(a.timestamp);
        var bDate = new Date(b.timestamp);
        if (aDate > bDate)
            return 1;
        if (aDate < bDate)
            return -1;
        return 0;
    });
    d3.selectAll("div.datarow").data(dataset, function(d) {return d.content})
        .transition()
        .duration(2000)
        .style("top", function(d,i) {return (40 + (i * 40))});
}

All this does is sort the array by date and re-binds it to the spreadsheet rows that are created earlier. And then it transitions the spreadsheet based on the updated array position.

But then, if you click the 'transition' button, it runs this function:

function transitionSheet() {
    d3.selectAll("div.datarow")
        .transition()
        .duration(2000)
        .style("top", function(d,i) {return (40 + (i * 40)) + "px"});
}

And restores the rows to their original position which would seem to indicate the i value was not changed. So, I'm confused. How does the i value change to make the rows move in the first function and then return to their initial value without any array.sort being done? My assumption is that because it's the selection order and so influenced by the order in the DOM that it's "sticky" but then how does the first function work properly?

Was it helpful?

Solution

Really interesting question.


Short answer

Index is not stored anywhere. Its value (i) is just reflection of the structure of the array that is being processed within your code.


A little longer answer

From d3 docs for selectAll()

 The elements will be selected in document traversal order (top-to-bottom).

This means that function transitionSheet() will always restore the order as it is in DOM tree.

However, in sortSheet(), after selection, data rebinding is performed with the call to data(). That causes changing order of elements in the array (but not in the DOM tree, which allows subsequent call to transitionSheet() and the effect of restoring original order)!

In conclusion, you can view index i just as a temporary artifact, related to the array that you manipulate in your code at given point, not as a "property" of the data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top