# Calculating the total of values in JS function and displaying it on a row

I have a custom script I’m using in google sheets to pull data from a sheet and to display on a different sheet. I want it to calculate the sum of hours (the last values in the arrays) and display it in the "week x total x" row pushed by the function. I cant seem to figure out how to do this.

Here is the function

``````var array = [
['123', 'x', 3, 3],
['123', 'x', 2, 3],
['123', 'x', 3, 3],
['123', 'x', 4, 3],
['123', 'x', 2, 3],
['123', 'x', 4, 3],
['123', 'x', 4, 3],
['123', 'x', 3, 3],
['123', 'x', 3, 3],
['123', 'x', 3, 3],
]

function sortByWeek(array) {
for (var i = 1; i < array.length; i++) {

// sort tasks by week number
for (var j = 0; j < i; j++) {
if (array[i] < array[j]) {
var x = array[i];
array[i] = array[j];
array[j] = x;
}
}
}

// insert rows between different weeks;
var arrayFinal = [];
let same = array;
let total = 0;
for (var e = 0; e < array.length; e++) {

// If week num is same as previous -> add item
if (array[e] === same) {
total = total + array[e];
arrayFinal.push(array[e]);
}

// If week num is no the same as previous -> add rows -> add item
else {

// If not first -> add rows
if (!(e === 0)) {
var rows = [
["Week " + same + " total " + total]
];
for (var s = 0; s < rows.length; s++) {
arrayFinal.push(rows[s]);
}
total = 0;
}

arrayFinal.push(array[e]);
}
same = array[e];
}
for (var s = 0; s < rows.length; s++) {
arrayFinal.push(rows[s]);
}

for (var z = 0; z < arrayFinal.length; z++) {
console.log(arrayFinal[z].toString());
}
}
``````

This is what it gives me

``````123,x,2,3
123,x,2,3
Week 2 total 6
123,x,3,3
123,x,3,3
123,x,3,3
123,x,3,3
123,x,3,3
Week 3 total 12
123,x,4,3
123,x,4,3
123,x,4,3
Week 3 total 12
``````

But this is what i want it to give:

``````123,x,2,3
123,x,2,3
Week 2 total 6
123,x,3,3
123,x,3,3
123,x,3,3
123,x,3,3
123,x,3,3
Week 3 total 15
123,x,4,3
123,x,4,3
123,x,4,3
Week 3 total 9
``````

I have been staring this for too long and there must be super simple answer to this but i cant see it.

### 12 thoughts on “Calculating the total of values in JS function and displaying it on a row”

1. https://wardenafil.com does levitra work better than viagra

2. accutane 30 mg coupon – generic accutane price average cost of accutane

3. 4. stromectol 15 mg – ivermectin drug stromectol online

5. 6. local milfs
[url=”http://datingsitesover.com/?”]kathie lee gifford dating[/url]

7. http://gabenhim.com gabapentin 100mg capsules

8. cialis 2.5 price – online pharmacy no prescription cialis daily 5 mg

9. https://stromectolhumans.com/ ivermectin for humans

10. 11. 