How to sum elements of two multidimensional arrays?

别等时光非礼了梦想. 提交于 2021-01-28 14:29:37

问题


I have 2 multidimensional arrays:

[[230.0], [10.0], [12.0]]

[[50.0], [60.0], [89.0]]

And am trying to sum each element together and keep the same array structure. So it should look like:

[[280.0], [70.0], [101.0]]

I tried this:

 var sum = array1.map(function (num, index) {
  return num + array2[index];
   });

But I get this:

    [23050, 1060, 1289]

Any help would be appreciated. Thanks.


回答1:


Make it like this

var sum = array1.map(function (num, index) {
  return parseInt(num) + parseInt(array2[index]);
   });

You should have to make parseInt or parseFloat so it can convert string with them




回答2:


STEPS

  1. Iterate through every number in the array (array length).
  2. Sum the objects of the same index in both of the arrays.
  3. Push the sum into another array for the result. Use parseFloat if the input is string.
  4. (Optional) use .toFixed(1) to set decimal place to have 1 digit.

const arr1 = [[230.0], [10.0], [12.0]]
const arr2 = [[50.0], [60.0], [89.0]]

let sum = []
for (let i = 0; i < arr1.length; i++){ // Assume arr1 and arr2 have the same size
  let eachSum = parseFloat(arr1[i]) + parseFloat(arr2[i])
  sum.push([eachSum.toFixed(1)])
}

console.log(sum)



回答3:


You are trying to add two arrays structures inside the map function.

so one solution so you can see what is happening is this...

array1.map((a,i) => a[0] + array2[i][0])

screenshot from the console...




回答4:


The code, you use, takes only a single level, without respecting nested arrays. By taking na array with only one element without an index of the inner array and using an operator, like +, the prototype function toString is invoced and a joined string (the single element as string, without , as separator) is returned and added. The result is a string , not the result of a numerical operation with +.


You could take a recursive approach and check if the value is an array, then call the function again with the nested element.

function sum(a, b) {
    return a.map((v, i) => Array.isArray(v) ? sum(v, b[i]) : v + b[i]);
}

console.log(sum([[230], [10], [12]], [[50], [60], [89]]))



回答5:


Inside map fn you should:

return parseInt(num) + parseInt(array2[index]);

This is happening because when you are trying to add them, these variable are arrays and not integers. So they are evaluated as strings and concatenated.



来源:https://stackoverflow.com/questions/54287082/how-to-sum-elements-of-two-multidimensional-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!