I have an array with multiple arrays inside. I would like to multiply the contents of each array.
Here is my code--currently not getting anything in console. The desired output is 3 numbers-- the result of multiplication of the three arrays
var arr = [
[1, 2, 3],
[3, 4],
[7, 8, 9]
]
var mult = 1
for (i = 0; i < arr.length; i ) {
for (j = 0; j < arr.length; j ) {
mult *= arr[i][j]
}
console.log(mult)
}
CodePudding user response:
You could map the result of the nested multiplying.
const
multiply = (a, b) => a * b,
array = [[1, 2, 3], [3, 4], [7, 8, 9]],
result = array.map(a => a.reduce(multiply, 1));
console.log(result);
CodePudding user response:
You can try this, it is easier using map and reduce functions. arr.map(array => array.reduce(arrayMult, 1))
is the multiplication of each inner array, like [ 6, 12, 504 ]
, and the last reduce is to multiply these values.
var arr = [[1, 2, 3],[3, 4],[7, 8, 9]];
const arrayMult = (prev, curr) => prev * curr;
const total = arr.map(array => array.reduce(arrayMult, 1)).reduce(arrayMult, 1);
CodePudding user response:
You should iterate over rows. So you need to change inner loop on this :
for (j = 0; j < arr[i].length; j )
const array = [
[1, 2, 3],
[3, 4],
[7, 8, 9]
];
for (i = 0; i < array.length; i ) {
let result = 1;
for (j = 0; j < array[i].length; j ) {
result *= array[i][j]
}
console.log(result);
}
CodePudding user response:
Nothing wrong with good old iterating; your existing approach only had one bug, on the inner loop you were still checking the length of the top-level array instead of the inner array; j
should range from 0 to arr[i].length
, not arr.length
.
An alternative approach uses map and reduce; comments below explain how it works:
var arr = [
[1, 2, 3],
[3, 4],
[7, 8, 9]
]
console.log(
arr.map(a => { // <-- calls a function on each element of arr,
// leaving the results in an array
return a.reduce( // <-- reducer is like map, calling a function
// on each element of a, but collects its results
// in a "collector" variable passed to each step
(val, sum) => {return val * sum}, // <-- multiply this value with
// the ones so far
1 // <-- initial value for the collector
)
})
)
CodePudding user response:
One approach was to iterate the array of arrays via map
which for each array puts the product of all of its items where the latter gets achieved via a multiplying reduce
task.
console.log([
[1, 2, 3],
[3, 4],
[7, 8, 9],
].map(arr =>
arr.reduce((x, y) => x * y)
));