-
Notifications
You must be signed in to change notification settings - Fork 1
/
object_array_grouping_reduce.html
60 lines (57 loc) · 2.12 KB
/
object_array_grouping_reduce.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<!DOCTYPE html>
<html>
<head>
<title>Object Array Grouping using Reduce</title>
</head>
<body>
<h2>Object Array Grouping using Reduce</h2>
<div id="result"></div>
<script>
let ObjArr = [
{EmpId: 1, EmpName: 'Sam', Dept: 'Engg', Salary: 1000},
{EmpId: 2, EmpName: 'Smith', Dept: 'HR', Salary: 2000},
{EmpId: 3, EmpName: 'Denis', Dept: 'Engg', Salary: 4000},
{EmpId: 4, EmpName: 'Danny', Dept: 'IT', Salary: 3000},
{EmpId: 5, EmpName: 'David', Dept: 'HR', Salary: 4000},
{EmpId: 6, EmpName: 'John', Dept: 'IT', Salary: 2000},
];
var array_group_by = (records, keyForGroup) => {
const groupvalue = records.reduce((accumulator, currentValue) => {
var key = currentValue[keyForGroup];
if (!accumulator[key]) {
accumulator[key] = [];
}
accumulator[key].push(currentValue);
return accumulator;
}, {});
return groupvalue;
}
// Group by Dept
groupArr = array_group_by(ObjArr, 'Dept');
console.log('Group by Dept -----------------------------');
console.log(groupArr);
resultDiv = document.getElementById('result');
let data = "";
data += "<table border = '1'>";
groupObjKeys = Object.keys(groupArr);
for(let i = 0; i< groupObjKeys.length; i++) {
data += '<tr><th colspan="4">' + groupObjKeys[i] + '</th></tr>';
let objKeys = Object.keys(groupArr[groupObjKeys[0]][0]);
data += '<tr>';
for(let k=0; k<objKeys.length; k++) {
data += '<th>' + objKeys[k] + '</th>';
}
data += '</tr>';
for (let j=0; j<groupArr[groupObjKeys[i]].length; j++) {
data += '<tr>';
for(let k=0; k<objKeys.length; k++) {
data += '<td>' + groupArr[groupObjKeys[i]][j][objKeys[k]] + '</td>';
}
data += '</tr>';
}
}
data.innerHTML += '</table>';
resultDiv.innerHTML = data;
</script>
</body>
</html>