简体   繁体   中英

How to add elements of 2D array Javascript

I have a 2D array : [[1,2,3...],[4,5,6...],[7,8,9...]....] and so on.

Now I want to add elements of all the row and make it 1D array. Please watch the expected result below:

I want my result to be addition of all the elements of every row: [[1+2+3+...],[4+5+6+...],[7+8+9+...]]

Using Array.reduce , you can calculate the sum of the subArray and map that sum to each array using Array.map .

 const input = [[1,2,3],[4,5,6],[7,8,9]]; const output = input.map((item) => (item.reduce((acc, cur) => (acc + cur), 0))); console.log(output);

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