javascript - Using linq.js, I need to group by 2 fields and produce summary -
i have json
var obj = [{projectname:"test1", catname: "subtest1, marks1: 25, marks2: 45}, {projectname:"test1", catname: "subtest1", marks1: 45, marks2: 45}, {projectname:"test1", catname: "subtest2", marks1: 25, marks2: 45} {projectname:"test1", catname: "subtest2", marks1: 15, marks2: 25}, {projectname:"test2", catname: "subtest1", marks1: 35, marks2: 45} {projectname:"test2", catname: "subtest2", marks1: 20, marks2: 55} {projectname:"test2", catname: "subtest2", marks1: 25, marks2: 65} ]
i need group projectname , catname , sum each marks achieve result below
result = [{projectname:"test1", catname: "subtest1", marks1: 70, marks2: 90}, {projectname:"test1", catname: "subtest2", marks1: 40, marks2: 70} .....]
please help.
in plain javascript, use hash table reference same group , collect wanted data.
var data = [{ projectname: "test1", catname: "subtest1", marks1: 25, marks2: 45 }, { projectname: "test1", catname: "subtest1", marks1: 45, marks2: 45 }, { projectname: "test1", catname: "subtest2", marks1: 25, marks2: 45 }, { projectname: "test1", catname: "subtest2", marks1: 15, marks2: 25 }, { projectname: "test2", catname: "subtest1", marks1: 35, marks2: 45 }, { projectname: "test2", catname: "subtest2", marks1: 20, marks2: 55 }, { projectname: "test2", catname: "subtest2", marks1: 25, marks2: 65 }], groups = ['projectname', 'catname'], values = ['marks1', 'marks2'], grouped = data.reduce(function (hash) { return function (r, a) { var key = groups.map(function (k) { return a[k]; }).join('|'); if (!hash[key]) { hash[key] = {}; groups.foreach(function (k) { hash[key][k] = a[k]; }); values.foreach(function (k) { hash[key][k] = 0; }); r.push(hash[key]); } values.foreach(function (k) { hash[key][k] += a[k]; }); return r; }; }(object.create(null)), []); console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
version linq.js
var data = [{ projectname: "test1", catname: "subtest1", marks1: 25, marks2: 45 }, { projectname: "test1", catname: "subtest1", marks1: 45, marks2: 45 }, { projectname: "test1", catname: "subtest2", marks1: 25, marks2: 45 }, { projectname: "test1", catname: "subtest2", marks1: 15, marks2: 25 }, { projectname: "test2", catname: "subtest1", marks1: 35, marks2: 45 }, { projectname: "test2", catname: "subtest2", marks1: 20, marks2: 55 }, { projectname: "test2", catname: "subtest2", marks1: 25, marks2: 65 }], result = enumerable.from(data) .groupby( null, null, "{ projectname: $.projectname, catname: $.catname, marks1: $$.sum('$.marks1'), marks2: $$.sum('$.marks2') }", "$.projectname + ' ' + $.catname" ) .toarray(); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>
Comments
Post a Comment