Exploring frequently used methods of d3-array

Thilo Maier •
Last modified:

In this post, I will introduce you to the methods from d3-array, which I use often for data visualization. All examples run inside your browser using StackBlitz. StackBlitz currently supports Chromium-based and Firefox browsers only.

d3.min, d3.max and d3.extent

d3.min returns the minimum of an array using the natural order. Unlike Math.min, d3.min can handle missing values.

Let’s look at examples:

Likewise, d3.max returns the maximum. But what happens when the array, for which we would like to compute the maximum, contains objects? We can use an accessor function to retrieve a specific object property and transform it. In the following example, accessor

(d) => new Date(d.date);

extracts the date property and converts it into a JavaScript Date, which is used for comparison. This returns the most recent date (maximum). But what we need is the object with the most recent date, not just the most recent date. We can use d3.maxIndex to retrieve the index of the object with the most recent date.

Let’s look at examples:

To create an axis for numeric values with D3, you need to know the extent of the data along that axis. Extent means the minimum and maximum values. d3.extent returns an array with these values. It not only works with numeric values but with any values that have a natural sort order.

Let’s look at examples:

d3.range

d3.range returns an array of evenly spaced numbers. It has three arguments: start, stop and step. The only required attribute is stop. start defaults to 0 and step defaults to 1. start is inclusive, stop is exclusive.

Let’s look at examples:

As the floatingPointRange example shows, with d3.range you can run into the pitfalls of binary floating point math. You can fix this issue with Number.toFixed:

range(0, 1, 0.2).map((n) => n.toFixed(1));

And finally, if you try to create a range that causes an infinite loop, like the infiniteLoopRange, d3.range returns an empty array.

d3.ticks

d3.ticks generates an array of nicely-rounded numbers inside an interval [start, stop]. You have to pass in three arguments:

ticks(start, stop, count);

count is the number of ticks you are aiming for. But there is no guarantee that you will get this number. As the example below shows, you may get more or fewer ticks. The only thing that matters to d3.ticks is that the ticks are nicely rounded and inside [start, stop]. start and stop can be part of the ticks.

Let’s look at examples:

JavaScript Array methods

The d3-array documentation points out that you should master JavaScript’s built-in Array methods. d3-array complements them but does not replace them. You cannot do data visualization with JavaScript without knowing built-in Array methods like the back of your hand. Here is a cheat sheet that is a great starting point to understanding what some of the Array methods do: