JCss
JCss

Reputation: 107

Loop trough array and sum the length

EDITED:

Can someone help me with the problem below further. I have a class and an array inside the class. I want now use a for loop to sum the length of the previous array length, but for each iteration. If i == 1 I want sum the length of arr[0].x.length, If i == 2 I want sum the length of arr[0].x.length+arr[1].x.length, ect. It will be a lot of code to check each iteration.

Is there a simple way to do this? Instead allways use a new line like

if (i == 1) n = n + arr[i-1].x.length;
if (i == 2) n = n + arr[i-1].x.length+arr[i-2].x.length;
if (i == 3) n = n + arr[i-1].x.length+arr[i-2].x.length+arr[i-3].x.length;

function Class() {
 var x = [];
}

for (var i = 0; i < 9; i++) {
  arr[i] = new Class();
}

I add 4 items to each object.
arr[0].x.push(...)
arr[0].x.push(...)
...
arr[1].x.push(...)
arr[1].x.push(...)
...

var n = 0;

for (var i = 0; i < arr.length; i++) {
  if (i == 1) {
    n = n + arr[i-1].x.length;
  } else if (i == 2) {
    n = n + arr[i-1].x.length+arr[i-2].x.length;
  } else if (i == 3) {
    n = n + arr[i-1].x.length+arr[i-2].x.length+arr[i-3].x.length;
  }
  // ect.
}

Upvotes: 0

Views: 564

Answers (3)

benvc
benvc

Reputation: 15130

You could use reduce to get a total of all the lengths of your sub-arrays. For example:

const arrs = [[1, 2, 3], [4, 5, 6]];
const sum = arrs.reduce((acc, arr) => acc += arr.length, 0);
console.log(sum);
// 6

Upvotes: 3

Loc Mai
Loc Mai

Reputation: 217

Edit: benvc's answer is what you are looking for if you want to use reduce.

var arr = [[1,2,3], [4,5,6], [7]];
var n = 0;
for (var i = 0; i < arr.length; i++){
	n += arr[i].length;
}

console.log(n);

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138497

Just nest the loop two times: go over the indexes once then go up to that index from 0 in an inner loop:

for (var i = 0; i < arr1.length; i++) {
  for(var j = 0; j <= i; j++) {
     n = n + arr1[j].length;
  }
}

Upvotes: 1

Related Questions