Working with arrays

Most of our data is stored in arrays, and we spend a lot of our effort working with arrays to format and restructure data. This is why D3 provides a rich set of array-oriented utilities functions, making this task a lot easier. In this recipe, we will explore some of the most common and helpful utilities in this aspect.

Getting Ready

Open your local copy of the following file in your web browser:

https://github.com/NickQiZhu/d3-cookbook/blob/master/src/chapter3/working-with-array.html

How to do it...

The following code example shows some of the most common and helpful array utility functions offered by the D3 library and their effects:

<script type="text/javascript">
    // Static html code were omitted due to space constraint

    var array = [3, 2, 11, 7, 6, 4, 10, 8, 15];

    d3.select("#min").text(d3.min(array));
    d3.select("#max").text(d3.max(array));
    d3.select("#extent").text(d3.extent(array));
    d3.select("#sum").text(d3.sum(array));
    d3.select("#median").text(d3.median(array));
    d3.select("#mean").text(d3.mean(array));
    d3.select("#asc").text(array.sort(d3.ascending));
d3.select("#desc").text(array.sort(d3.descending));      d3.select("#quantile").text(
d3.quantile(array.sort(d3.ascending), 0.25)
);
d3.select("#bisect").text(
d3.bisect(array.sort(d3.ascending), 6)
    );

    var records = [
        {quantity: 2, total: 190, tip: 100, type: "tab"},
        {quantity: 2, total: 190, tip: 100, type: "tab"},
        {quantity: 1, total: 300, tip: 200, type: "visa"},
        {quantity: 2, total: 90, tip: 0, type: "tab"},
        {quantity: 2, total: 90, tip: 0, type: "tab"},
        {quantity: 2, total: 90, tip: 0, type: "tab"},
        {quantity: 1, total: 100, tip: 0, type: "cash"},
        {quantity: 2, total: 90, tip: 0, type: "tab"},
        {quantity: 2, total: 90, tip: 0, type: "tab"},
        {quantity: 2, total: 90, tip: 0, type: "tab"},
        {quantity: 2, total: 200, tip: 0, type: "cash"},
        {quantity: 1, total: 200, tip: 100, type: "visa"}
    ];

    var nest = d3.nest()
            .key(function (d) { // <- A
                return d.type;
            })
            .key(function (d) { // <- B
                return d.tip;
            })
            .entries(records); // <- C

    d3.select("#nest").html(printNest(nest, ""));

    function printNest(nest, out, i) {
        if(i === undefined) i = 0;

        var tab = ""; 
        for(var j = 0; j < i; ++j) 
            tab += " ";

        nest.forEach(function (e) {
            if (e.key)
                out += tab + e.key + "<br>";
            else
                out += tab + printObject(e) + "<br>";

            if (e.values)
                out = printNest(e.values, out, ++i);
            else
                return out;
        });

        return out;
    }

    function printObject(obj) {
        var s = "{";
        for (var f in obj) {
            s += f + ": " + obj[f] + ", ";
        }
        s += "}";
        return s;
    }
</script> 

The preceding code produces the following output:

d3.min => 2
d3.max => 15
d3.extent => 2,15
d3.sum => 66
d3.median => 7
d3.mean => 7.333333333333333
array.sort(d3.ascending) => 2,3,4,6,7,8,10,11,15
array.sort(d3.descending) => 15,11,10,8,7,6,4,3,2
d3.quantile(array.sort(d3.ascending), 0.25) => 4
d3.bisect(array.sort(d3.ascending), 6) => 4

tab100{quantity: 2, total: 190, tip: 100, type: tab, }{quantity: 2, total: 190, tip: 100, type: tab, }0{quantity: 2, total: 90, tip: 0, type: tab, }{quantity: 2, total: 90, tip: 0, type: tab, }{quantity: 2, total: 90, tip: 0, type: tab, }{quantity: 2, total: 90, tip: 0, type: tab, }{quantity: 2, total: 90, tip: 0, type: tab, }{quantity: 2, total: 90, tip: 0, type: tab, }visa200{quantity: 1, total: 300, tip: 200, type: visa, }100{quantity: 1, total: 200, tip: 100, type: visa, }cash, }0{quantity: 1, total: 100, tip: 0, type: cash, }{quantity: 2, total: 200, tip: 0, type: cash, }

How it works...

D3 provides a variety of utility functions to help perform operations on JavaScript arrays. Most of them are pretty intuitive and straightforward, however, there are a few intrinsic ones. We will discuss them briefly in this section.

Given our array as [3, 2, 11, 7, 6, 4, 10, 8, 15]:

  • d3.min: This function retrieves the smallest element, that is, 2
  • d3.max: This function retrieve the largest element, that is, 15
  • d3.extent: This function retrieves both the smallest and the largest element, that is, [2, 15]
  • d3.sum: This function retrieves the addition of all elements in the array, that is, 66
  • d3.medium: This function finds the medium, that is, 7
  • d3.mean: This function calculates the mean value, that is, 7.33
  • d3.ascending / d3.descending: The d3 object comes with a built-in comparator function that you can use to sort the JavaScript array
    d3.ascending = function(a, b) {  return a < b ? -1 : a > b ? 1 : 0; }
    d3.descending = function(a, b) {  return b < a ? -1 : b > a ? 1 : 0; }
  • d3.quantile: This function calculates the quantile on an already sorted array in ascending order, that is, quantile of 0.25 is 4
  • d3.bisect: This function finds an insertion point that comes after (to the right of) any existing element of an already sorted array, that is, bisect (array, 6) produce 4
  • d3.nest: D3's nest function can be used to build an algorithm that transforms a flat array-based data structure into a hierarchical nested structure, that is, particularly suitable for some types of visualization. D3's nest function can be configured using the key function chained to nest, as seen on lines A and B:
        var nest = d3.nest()
                .key(function (d) { // <- A
                    return d.type;
                })
                .key(function (d) { // <- B
                    return d.tip;
                })
                .entries(records); // <- C

    Multiple key functions can be provided to generate multiple levels of nesting. In our case the nesting consists of two levels, first by the type amount and then by the tip amount, as demonstrated in the output below:

    tab
     100
      {quantity: 2, total: 190, tip: 100, type: tab, }
      {quantity: 2, total: 190, tip: 100, type: tab, }

    Finally, the entries() function is used to supply the flat array-based data set as shown on line C.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset