0

In a multi-dimensional array, how can I add a new dimension that is the sum of all of previous values of one of the other dimensions?

What I have:

var myarray = [[5,"a"],[10,"a"],[3,"a"],[2,"a"]];

What I want:

var newArray = [[5,"a",5],[10,"a",15],[3,"a",18],[2,"a",20]];

I am trying to turn this example (second answer, second code block):

var myarray = [5, 10, 3, 2];

var result = myarray.reduce(function(r, a) {
  if (r.length > 0)
    a += r[r.length - 1];
  r.push(a);
  return r;
}, []);

// [5, 15, 18, 20]

And apply it like this:

var myarray = [[5,"a"],[10,"a"],[3,"a"],[2,"a"]];

var result = myarray.reduce(function(r, a) {
  if (r.length > 0)
    a += r[0][r.length - 1];
  r[2].push(a);
  return r;
}, []);

// [[5,"a",5],[10,"a",15],[3,"a",18],[2,"a",20]];

But I can't find an effective way to separate out the first value in order to run reduce on it. I tried foreach, but that isn't returning an array:

var firstValue = myarray.forEach(function(value, index) {
console.log(value[0]);
})

So, I'm thinking take that foreach output and turn it into an array somehow to operate on, then push it back in. But it's seeming very convoluted. Can anyone point me in the right direction?

Thanks.

2 Answers 2

1

For reducing the array and only pulling the first element from each array, you actually need to build an array with the foreach loop.

Create an array outside the loop and use array.push(value) to build the other array.

var firstValues = [];
myarray.forEach(function(value, index) {
    firstValues.push(value);
});

My preferred solution:

Since you're already looping through the array, you can instead do a lot of the logic within just one loop.

var currentSum = 0;
myarray.forEach(function(value, index) {
    currentSum += value[0]; //add to the running sum
    value.push(currentSum); //append the running sum to the end of this inner array
});

Here's a demo via jsfiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your quick reply and detailed explanation. This works great. Thinking ahead about performance is the only reason I went with the other answer. Apologies, I should have mentioned the volume of data. Thanks!
0

a simple for loop should do it

var sum = 0;
    for (var i = 0; i < myarray.length; i++) {
        sum = sum + (myarray[i][0]);
        myarray[i].push(sum);

    }

console.log(myarray);

Fiddle link

1 Comment

Thank you! That works great. Both answers are great. I am choosing this answer as the right one simply because I've read that for is faster than forEach. For the way I'll be using this, it'll be operating on a lot of values and that will help. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.