Scott Baldridge
asked on
Loop through object and sum totals
Hello, I have some employee data in employeeGrid object which consists of employee, hours.
How can I loop through employeeGrid and sum up the hours for each employee. Once I get the list of employees and their hours I want to add that to a div .EmployeeHours.
With my code below, I just get a list of the employees and their hours with dupes and no sums.
Here is some sample data:
Dan, 8
Dan, 4
Dan, 2
Julie, 8
Mark, 8
The EmployeeHours should look like this:
Dan 14
Julie 8
Mark 8
function setEmployeeHours(employeeG rid){
$('.EmployeeHours').html(' ');
for (var key in employeeGrid) {
var obj = employeeGrid[key];
if (obj.employee) {
$('.EmployeeHours').append (obj.emplo yee+ " " + obj.hours + "</br>");
}
}
}
How can I loop through employeeGrid and sum up the hours for each employee. Once I get the list of employees and their hours I want to add that to a div .EmployeeHours.
With my code below, I just get a list of the employees and their hours with dupes and no sums.
Here is some sample data:
Dan, 8
Dan, 4
Dan, 2
Julie, 8
Mark, 8
The EmployeeHours should look like this:
Dan 14
Julie 8
Mark 8
function setEmployeeHours(employeeG
$('.EmployeeHours').html('
for (var key in employeeGrid) {
var obj = employeeGrid[key];
if (obj.employee) {
$('.EmployeeHours').append
}
}
}
You could use a map keyed on the employee names. As you loop through the employees in the grid, look up the name in the map and increment the value by the number of hours in that row. Finally, print the key value pairs of the map to get the total hours worked.
I made a lot of assumptions, but this should be what you're looking for
http://codepen.io/anon/pen/mEaYPE?editors=1010
unless you have an ordered list you'll have to do a nested for loop.
http://codepen.io/anon/pen/mEaYPE?editors=1010
unless you have an ordered list you'll have to do a nested for loop.
var employees = [{
"employee": "Dan","hours": 8 }, {
"employee": "Dan","hours": 4 }, {
"employee": "Dan","hours": 2 }, {
"employee": "Julie","hours": 8 }, {
"employee": "Mark","hours": 8 }];
var result = [];
for (var i in employees) {
var append = true;
var emp = employees[i]
if (result.length === 0) {
result.push(emp);
continue;
}
for (var x in result) {
var pushedEmp = result[x];
if (pushedEmp.employee === emp.employee) {
pushedEmp.hours += emp.hours;
append = false;
break;
}
}
if (append)
result.push(emp);
}
for (var r in result) {
var emp = result[r];
var outputDiv = document.getElementById("output");
var div = document.createElement("div");
div.innerText = emp.employee + " " + emp.hours;
outputDiv.appendChild(div);
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks much appreciated!