D3.js nest() Function

D3.js is a library built with javascript and particularly used for data visualization. D3.nest() function is used to group the data as groupBy clause does in SQL. It groups the data on the basis of keys and values.

Syntax:

d3.nest()

Parameters: This function does not accept any parameters.

Return Value: It returns the object with several properties as entries, keys, values, map, sort.

Example 1: In this example, the data is to be grouped on the basis of key “manufactured” we can group the data on the basis of multiple keys as well.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" path1tent=
        "width=device-width, initial-scale=1.0">
  
    <script src="https://d3js.org/d3.v4.min.js">
    </script>
  
    <title>
        D3.js d3.nest() Function
    </title>
</head>
  
<body>
    <script>
        var cars = [
            { name: "car1", manufactured: "1950", model: "s51" },
            { name: "car1", manufactured: "1950", model: "s51" },
            { name: "car1", manufactured: "1951", model: "s50" },
            { name: "car1", manufactured: "1951", model: "s50" },
        ];
        var groupedData = d3.nest()
            .key(function (d) { return d.manufactured; })
            .entries(cars);
        console.log("ArrayData :", groupedData);
        console.log("ArrayData[0] :", groupedData[0]);
        console.log("ArrayData[1] :", groupedData[1]);
    </script>
</body>
  
</html



Output:

Example 2: This example explains the grouping of data on the basis of multiple keys.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" path1tent=
        "width=device-width, initial-scale=1.0">
  
    <script src="https://d3js.org/d3.v4.min.js">
    </script>
  
    <title>
        D3.js d3.nest() Function
    </title>
</head>
  
<body>
    <script>
        var cars = [
            { name: "car1", manufactured: "1950", model: "s51" },
            { name: "car1", manufactured: "1950", model: "s51" },
            { name: "car1", manufactured: "1951", model: "s50" },
            { name: "car1", manufactured: "1951", model: "s50" },
        ];
        var groupedData = d3.nest()
            .key(function (d) { return d.manufactured; })
            .key(function (d) { return d.model; })
            .entries(cars);
        console.log("ArrayData :", groupedData);
        console.log("ArrayData[0] :", groupedData[0]);
        console.log("ArrayData[1] :", groupedData[1]);
    </script>
</body>
  
</html>



Output: