1

I have a 2D array which is structured like so:

enter image description here

I would like to sum the values relative to their index ie. (-10000 + 100 + 100 + -100). Then store these in a separate array which would look something like:

[[500], [-10100], [9000], [18000], [18000]]

I would imagine I'd have to use map and reduce to achieve this, but I'm not having much luck.

Here's what I currently have:

for (var i=1; i<totals.length; i++) {
    for (var z=0; z<totals[i].length; z++) {
        console.log(totals[i][z] = totals[i-1][z] + totals[i][z]);
    }
}

However, that seems to output the following:

enter image description here

If someone could push me in the right direction, that would be awesome.

2 Answers 2

5

Use Array.prototype.map() and Array.prototype.reduce():

const arrays = [
  [500],
  [-10000, 100, 100, -100],
  [9000],
  [9000, 9000],
  [9000, 9000]
];

const result = arrays.map(xs => xs.reduce((sum, x) => sum + x, 0));

console.log(JSON.stringify(result));

If you want each sum in an array, just enclose it in brackets:

const arrays = [
  [500],
  [-10000, 100, 100, -100],
  [9000],
  [9000, 9000],
  [9000, 9000]
];

const result = arrays.map(xs => [xs.reduce((sum, x) => sum + x, 0)]);

console.log(JSON.stringify(result));

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

2 Comments

Perfect. Thanks for that. I take it .reduce() flattens the array?
@Charlie Coplestone, It iterates over the array and allows you to modify an accumulator, here the sum, which is returned at the end.
1

My recommendation is to follow jo_va approach: it is far more declarative and simpler.

Having said that, if you want to use for loop, here is your corrected version

const arrays = [
  [500],
  [-10000, 100, 100, -100],
  [9000],
  [9000, 9000],
  [9000, 9000]
];

let results = [];
for (var i = 0 ; i < arrays.length; i++) {
    let sum = 0;
    for (var z = 0; z < arrays[i].length; z++) {
        sum += arrays[i][z]
    }
    results.push(sum);
}
console.log(results);

As you can see the result is the same, but in comparison

  • it is more imperative, rather than declarative
  • it is more verbose, and larger, therefore, more error-prone

Your problem was that you were updating the array as well iterating it, causing the iteration to broke. You were not accesing the array properly either.

If you neeeded to return an array of results, it is better to create a new and push results there.

Again, consider using map + reduce; it is the best approach. I just wanted to show you the option you wanted to use

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.