How do I multiply an array of numbers with another array of numbers in javascript

Viewed 166

I've been trying to make an array of numbers be able to times another array of numbers without doing array.join("") * array2.join("").

I've tried a lot of methods such as:

var input = [3, 6, 4];
var scalar = 5;
var output = input.map(x => x * scalar); // [15, 30, 20]

Although that's only one number the array can multiply to.

I'd like a function that can do:

var array = [ 1, 3, 2 ];
var array2 = [ 5, 3, 8, 2, 3, 5, 2 ];
someFunction(array, array2);
// [ 7, 1, 0, 4, 7, 0, 4, 6, 4 ]

Please note I don't want it to be something like

array.join("") * array2.join("")

I'm willing to give all my reputation as a bounty if someone is able to answer my question.

1 Answers

If scientific notation is the problem, turn the arrays into BigInts instead.

var array = [ 1, 3, 2, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5 ];
var array2 = [ 5, 3, 8, 2, 3, 5, 2, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5 ];
const someFunction = (arr1, arr2) => [...String(
  BigInt(arr1.join('')) * BigInt(arr2.join(''))
)].map(Number);
console.log(someFunction(array, array2));

Related