-1

Using JavaScript, I am looping through an array of values.

var values = [1, 2, 1, 3, 1, 3, 4, 1]
for (let i = 0; i < values.length; i++) {
  console.log(values[i])
}

I want to get the sum for each group of 4. I could do this in multiple for loops by using:

var values = [1, 2, 1, 3]
var sum1 = 0
for (let i = 0; i < values.length; i++) {
  sum1 += parseInt(values[i]);
}

var values = [1, 3, 4, 1]
var sum2 = 0
for (let i = 0; i < values.length; i++) {
  sum2 += parseInt(values[i]);
}

How can I group by 4 and get the sum of the values for each group by using one for loop?

cfoster5
  • 1,696
  • 5
  • 28
  • 42
  • `parseInt`? does it has a special meaning? – Nina Scholz Jul 01 '18 at 19:07
  • @NinaScholz Unnecessary for this example, really. Just converts a string to a integer. – cfoster5 Jul 01 '18 at 19:08
  • 2
    Possible duplicate of [Split array into chunks of N length](https://stackoverflow.com/questions/11318680/split-array-into-chunks-of-n-length). Also see [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Methods_2) methods. – Sebastian Simon Jul 01 '18 at 19:08

3 Answers3

2

Can slice() the array and reduce() each sub array

var values = [1, 2, 1, 3, 1, 3, 4, 1]

var sums =[];

for(let i=0; i< values.length; i=i+4){
   const subArr= values.slice(i,i+4);
   const sum = subArr.reduce((a,c)=>a+c)
   sums.push(sum)
}

console.log(sums)
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

You can use a counter. Reset the counter and sum variable when it reaches the group limit, like below example :

var values = [1, 2, 1, 3, 1, 3, 4, 1];
var result = [];
var counter = 0;
var sum = 0;
for(var i = 0; i < values.length; i++){
  counter++;
  sum += values[i];
  if(counter === 4 || i === values.length-1){
    result.push(sum);
    counter = 0;
    sum = 0;
  }
}

  
  console.log(result);
amrender singh
  • 7,949
  • 3
  • 22
  • 28
0

You could take an array as result set and divide the index by 4 and take the integer value for adding the value.

var values = [1, 2, 1, 3, 1, 3, 4, 1],
    grouped = values.reduce((r, v, i) => {
        var k = Math.floor(i / 4);
        r[k] = r[k] || 0;
        r[k] += v;
        return r;
    }, []);
    
console.log(grouped);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392