i want to sum of Array like this
1 1 2 =4
2 2 1 =5
3 3 1 =7
= = =
6 6 4
i want to print like this sum of Array Using java script in html.
Let's see how to find the sum of the 2D array using the map function. Initialize the 2D array using lists. Pass the function sum and 2D array to the map function. Find the sum of resultant map object and print it.
Start by breaking the problem down into smaller pieces first. I defined a basic sum
function which is defined using an even more basic add
function. map
ping sum
over the input array will give you the horizontal sums.
The vertical sums are little more tricky, but not too tough. I defined a transpose
function which rotate our matrix. Once we rotate, we can sum
the rows the same way.
This solution works on any MxN matrix
// generic, reusable functions
const add = (x,y) => x + y
const sum = xs => xs.reduce(add, 0)
const head = ([x,...xs]) => x
const tail = ([x,...xs]) => xs
const transpose = ([xs, ...xxs]) => {
const aux = ([x,...xs]) =>
x === undefined
? transpose (xxs)
: [ [x, ...xxs.map(head)], ...transpose ([xs, ...xxs.map(tail)])]
return xs === undefined ? [] : aux(xs)
}
// sample data
let numbers = [
[1,1,1],
[2,2,2],
[3,3,3],
[4,4,4]
]
// rows
console.log(numbers.map(sum))
// [ 3, 6, 9, 12 ]
// columns
console.log(transpose(numbers).map(sum))
// [ 10, 10, 10 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With