Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to multiply n arrays of the same length with each other?

I want to multiply arrays of the same length. The total number of arrays (input.length) is known, but it can be everything between 0 and n.

const input = [
  [1, 2, 3, 4],
  [1, 2, 3, 4],
  [1, 2, 3, 4],
  [1, 2, 3, 4]
];

const output = [1, 16, 81, 256];
// 1*1*1*1, 2*2*2*2, 3*3*3*3, 4*4*4*4

I found solutions on SO for multiplying two arrays by mapping them against each other, but not for n arrays.

I am grateful for any hints.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want to multiply arrays, the best solution would be the Array#Reduce function

You here only need to introduce a function as I did with multiplyArray to handle how to compute to arrays together

const input = [
  [1, 2, 3, 4],
  [1, 2, 3, 4],
  [1, 2, 3, 4],
  [1, 2, 3, 4]
];

const multiplyArray = (arr1, arr2) => {
  if(arr1.length !== arr2.length) {
    throw new Error('Array have not the same length');
  }
  
  arr1.forEach((elem, index) => {
    arr1[index] = elem * arr2[index]
  })
  
  return arr1
}

const output = input.reduce((acc, curr) => {
  if(acc === null) return curr
  
  return multiplyArray(acc, curr)
}, null)

console.log(output)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading