Find the sum of a 2d array in a Javascript wid string and column wise

I want to sum an array like this

1 1 2 = 4

2 2 1 = 5

3 3 1 = 7

= = =

6 6 4

I want to print this sum of an array using java script in html.

+4
source share
1 answer

First, start breaking up the problem into smaller pieces first. I defined a basic sum function that is defined using the even more basic add function. map ping sum over the input array will give you horizontal sums.

Vertical amounts are a little trickier, but not too tough. I defined a transpose function that rotates our matrix. Once we rotate, we can sum lines in 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 ] 
+13
source

Source: https://habr.com/ru/post/1485922/


All Articles