简体   繁体   中英

How to add elements of array within an array in JavaScript?

How do we add elements of an array within an array in JavaScript? As in if I have something like

positions=[[1,2],[2,7],[3,9]]

How do I get the summation of the first element within each array within the primary array, the summation of the second element of each array within the array. So I would want to compute

x1=1+2+3
y1=2+7+9

A simple for -loop would suffice and would also be the most efficient solution and most widely supported solution (all other solutions proposed here will break on older browsers unless polyfilled):

var x1 = 0, y1 = 0, len = positions.length;
for (var i = 0; i < len; i++)
{
    x1 += positions[i][0];
    y1 += positions[i][1];
}

Or alternatively, you could use the forEach method:

var x1 = 0, y1 = 0;
positions.forEach(function(a) { x1 += a[0]; y1 += a[1]; });

But if you want to get fancy, you can use the reduce method like this:

var x1 = positions.reduce(function(x, a) { return x + a[0]; }, 0);
var y1 = positions.reduce(function(x, a) { return x + a[1]; }, 0);
alert([x1, y1]); // 6,18

And you could even compute both sums at once like this:

var xy = positions.reduce(function(x, a) { return [x[0] + a[0], x[1] + a[1]]; }, [0, 0]);
alert(xy); // 6,18

I made little fiddle for you. Check it out. It should answer your question.

http://jsfiddle.net/rkhadse_realeflow_com/xTup9/16/

<script>
var positions = [
    [1, 2],
    [2, 7],
    [3, 9]
];

console.log(positions[1][1]);
var i = 0;
var output = "";
for (i = 0; i < positions.length; i++) {
    output = output + "(" + positions[i][0] + "," + positions[i][1] + ")";
}

console.log(output);

var x1 = 0;
var y1 = 0;
for (i = 0; i < positions.length; i++) {
    x1 = x1 + positions[i][0];
    y1 = y1 + positions[i][1];    
}
console.log(x1);
console.log(y1);
</script>

Code with notes:

var positions = [[1,2],[2,7],[3,9]]; // Create your array of numbers
x1 = y1 = 0; // Baseline x1 and y1

// Loop through your array (this is standard for loop)
for (var i = 0, len = positions.length; i < len; i++) {
    x1 += positions[i][0]; // Add first array element to existing count
    y1 += positions[i][1]; // Add second array element to existing count
}

// Log results
console.log(x1);
console.log(y1);

Here's a working example: http://jsfiddle.net/6ras8/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM