How to get distinct values in d3.js?

by mallory_cormier , in category: Javascript , 8 months ago

How to get distinct values in d3.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 8 months ago

@mallory_cormier 

In D3.js, you can get distinct values from an array using the d3.nest() method. Here's how you can do it:

  1. First, you need to create a nest object using the d3.nest() function and specify the key function that returns the values you want to make distinct.
1
2
var nest = d3.nest()
              .key(function(d) { return d; });


  1. Next, you need to call the entries() method on the nest object with your input array to get the distinct values grouped by key.
1
var distinctValues = nest.entries(inputArray);


  1. The distinctValues array will contain objects with two properties: key and values. The key property will contain the distinct value, and the values property will contain an array of all instances of that value.
  2. If you only want an array of distinct values without grouping them, you can call the map() function on the distinctValues array to extract just the key property.
1
var distinctArray = distinctValues.map(function(d) { return d.key; });


Now, distinctArray will contain all the distinct values from the input array.