如何从dataTables中获得不同的值。从下面的图片中可以看到

javascript - 如何从dataTables中获得不同的值并使用JS对特定字段的总和求和-LMLPHP

您将看到“ Course 1”具有相同的值。我想从“课程名称”中获取所有不同的值,同时使用JS从DataTables中的相同不同值中添加所有等效的“学生”。

我希望回报是

“课程1,4学生”

编辑:

HTML代码:

<table class="table" id="bookingReport" cellspacing="0" width="100%">
    <thead class="thead-inverse">
        <tr>
            <th><h4>Course Names</h4></th>
            <th><h4>Names</h4></th>
            <th><h4>Dates</h4></th>
        </tr>
    </thead>
</table>


JS代码:

"dataSrc": function(result) {
    var obj, id, paymentMethod;
    var validatedResult = [];

    $.each(result.aaData, function(index, value) {
        var givenName, surname, organisationName;

        id = value.id;
        dateCreated = value.dateCreated;



        $.each(value.bookingDetail, function(i, v) {


            $.each(v.student.studentCourseDetail, function(ii, sd) {
                obj = new Object();

                obj["id"] = sd.id;
                obj["surname"] = surname;
                obj["givenName"] = givenName;
                obj["dateCreated"] = dateCreated;
                obj["courseName"] = sd.courseName;


                validatedResult.push(obj);



            });




        });

    });

    return validatedResult;

}, },

"aoColumns": [{
        "data": "courseName"
    }, {
        "data": "givenName"
    }, {
        "data": "dateCreated"
    }

],

最佳答案

要计算分配给每门课程的人数,可以使用数组的reduce函数。给定下面的学生数组,您可以轻松计算结果。



var bookingList = [{
    id: 1,
    name: 'Alice',
    courseName: 'Physics'
  },
  {
    id: 2,
    name: 'Bob',
    courseName: 'Physics'
  },
  {
    id: 3,
    name: 'Emily',
    courseName: 'Math'
  },
  {
    id: 1,
    name: 'Alice',
    courseName: 'Math'
  },
  {
    id: 4,
    name: 'Jane',
    courseName: 'Biology'
  },
  {
    id: 5,
    name: 'Dan',
    courseName: 'Chemistry'
  }
]

var result = bookingList.reduce(function(prevValue, currValue, index, array) {
  var bookingEntry = array[index]
  if (prevValue[bookingEntry.courseName] == null) {
    prevValue[bookingEntry.courseName] = 1
  } else {
    prevValue[bookingEntry.courseName]++
  }

  return prevValue
}, {});

console.log(result)

07-24 16:46