skip to Main Content

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.

3

Answers


  1. 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)
    Login or Signup to reply.
  2. const input = [
      [1, 2, 3, 4],
      [1, 2, 3, 4],
      [1, 2, 3, 4],
      [1, 2, 3, 4]
    ]
    
    const result = input.reduce((filtered, current) => {
      filtered.push(current.reduce((accumulator, currNum) => {
        accumulator.push(Math.pow(currNum, input.length))
        return accumulator
      }, []))
    
      return filtered
    }, [])
        
    console.log(result)
    
    Login or Signup to reply.
  3. You can use Array.prototype.map() combined with Array.prototype.reduce() and Array.prototype.every() to create a function multiplyAcrossArrays with validation to check length of sub-arrays

    Code:

    const input = [[1, 2, 3, 4],[1, 2, 3, 4],[1, 2, 3, 4],[1, 2, 3, 4]]
    
    const multiplyAcrossArrays = (input) => {
      if (!input.every(subArray => subArray.length === input[0].length)) {
        throw new Error('All sub-arrays must have the same length')
      }
    
      return input[0].map((_, i) => input.reduce((a, c) => a * c[i], 1))
    }
    
    console.log(multiplyAcrossArrays(input))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search