To convert a two-dimensional array in vanilla JS to map, redoce

Asked 1 years ago, Updated 1 years ago, 39 views

//2D array
vararr = [
  [1,2,3],
  [2,3,4],
  [5,6,7]
]

I'd like to sum up each array element of a two-dimensional array like ↓.

[
  [6],
  [9],
  [18]
]
vararr1=arr.map(function(val){
  val.reduce(function(a,b){return a+b})
})

I thought it would match the answer you asked in
The result is [null, null, null].
If anyone understands, please reply.

javascript

2022-09-30 21:23

2 Answers

If you add a return to the function in the map, it will work properly.

vararr1=arr.map(function(val){
    return value.reduce(function(a,b){return a+b})
})


2022-09-30 21:23

It worked.

arr.map(function(val){
  return val.reduce (function(a,b) {return a+b;})
})

Then I did a great job.

arr.map(function(val){return)
   val.reduce (function(a,b) {return a+b;})
})

return would not work.
Thank you


2022-09-30 21:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.