首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

动态DataTable Group by和聚合函数

在动态DataTable中,要根据某个列对数据进行分组并应用聚合函数,您可以使用rows().data()方法获取数据,然后使用JavaScript的reduce()方法对数据进行分组和聚合

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>DataTable Group by and Aggregate Functions</title>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
</head>
<body>
   <table id="example" class="display" style="width:100%">
       <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
       <tbody>
            <!-- Add your data here -->
        </tbody>
    </table>

   <script>
        $(document).ready(function() {
            var table = $('#example').DataTable();

            // Group by "Office" column and calculate the sum of "Salary" column
            var groupedData = table.rows().data().reduce(function(accumulator, currentValue) {
                var office = currentValue[2]; // Office column index
                var salary = parseFloat(currentValue[5]); // Salary column index

                if (!accumulator[office]) {
                    accumulator[office] = {
                        office: office,
                        totalSalary: 0
                    };
                }

                accumulator[office].totalSalary += salary;
                return accumulator;
            }, {});

            console.log(groupedData);
        });
    </script>
</body>
</html>

在这个示例中,我们首先创建了一个DataTable实例。然后,我们使用rows().data()方法获取表格中的所有数据,并使用reduce()方法对数据进行分组和聚合。我们根据“Office”列对数据进行分组,并计算每个组的“Salary”列之和。

最后,我们将分组后的数据打印到控制台。您可以根据需要修改此示例,以便将分组后的数据显示在表格中或用于其他目的。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券