简体   繁体   English

如何将多维数组内的所有值相乘

[英]How to multiply all values inside multidimensional array

I have output like this(Multi dimensional array); 我有这样的输出(多维数组);

    (4) [Array(3), Array(2), Array(2), Array(2)]
    0: (3) [9, 8, 9]
    1: (2) [5, 6]
    2: (2) [6, 7]
    3: (2) [4, 4]
    length: 4
    __proto__: Array(0)

I would like to get each value and multiply them and return the value. 我想获取每个值并将它们相乘并返回值。 How do I do that? 我怎么做?

You can use .reduce to do that. 您可以使用.reduce来做到这一点。

You just need to join the array to get a valid number. 您只需要加入数组即可获得有效数字。

[9, 8, 9].join('') == 989

After, you can get your desired output by multiplying them 之后,将它们相乘即可得到所需的输出

See example : 参见示例:

 var arr = [[9, 8, 9],[5, 6],[6, 7],[4, 4]]; var res = arr.reduce(function (a,b) { return a * b.join(''); }, 1); console.log(res) 

Like this? 像这样?

 function multiply(array){ var x=1 for(i in array){ x*=parseInt(array[i].join("")) } return x } var something=[[9,8,9],[5,6],[6,7],[4,4]] console.log(multiply(something)) 
I hope this will help! 我希望这个能帮上忙!

You can use reduce. 您可以使用reduce。

 const data = [[9, 8, 9], [5, 6], [6, 7], [4, 4]]; const result = data.reduce((acc, val) => val.join('') * acc, 1); console.log(result); 

First of all you should probably check why the numbers are coming as an array if you need to join them into one number. 首先,如果您需要将数字连接成一个数字,则可能应该检查为什么数字会作为数组出现。 But, working with what you've given to us... 但是,使用您提供给我们的东西...

First, you have to get each inner array and join it as one single number. 首先,您必须获取每个内部数组并将其作为一个数字连接。 The best approach I can imagine is casting each number inside to a string, concatenating them, and casting back to Number, like this: 我能想象到的最好方法是将每个数字强制转换为字符串,将它们连接起来,然后强制转换为Number,如下所示:

const numbersArray = outerArray
  .map(innerArray =>
    innerArray.map(number => number.toString()).join(''))
  .map(Number)

After having mapped the array, you can then reduce it to a single number, multiplying along the way (and starting at 1 since we don't want an initial value to change the result): 映射完数组后,您可以将其reduce为一个数字,并乘以1(从1开始,因为我们不希望初始值更改结果):

numbersArray.reduce((product, each) => product * each, 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM