hi i recently came across this beginners JS challenge where you have to multiply the nested array of numbers using nested for loops . Like 1x2 and then 1x2x3 and so one . multi = [[1, 2], [1, 2, 3], [1, 2, 3, 4]]
This is the code i wrote. It works but i want to know if i can make it shorter? and sorry for the #FRIENDS i hope it doesn’t violate any code of this forum .
var multi = [[1, 2], [1, 2, 3], [1, 2, 3, 4]];
var product = [];
var i;
var j;
for (i = 0; i < multi.length; i += 1) {
var b = 1;
for (j = 0; j < multi[i].length; j += 1) {
b = b * multi[i][j];
}
product.push(b);
}
console.log(product);
you should be able to make your code shorter by using array method reduce @ArielLeslie mentioned in post #2 .
it will help you to get rid of second level of for loop, because reducer accepts array as input, so no need to loop over nested arrays
The nested loop already only has one line in it, so I’m not sure how much shorter you are expecting to get it. Maybe I’m not understanding what you are hoping to accomplish.
Also be careful to not overshorten codes too much. Sometimes it’s not really worth to risk legibility for a short code.
Especially if the code you are working on is shared with someone else.
var multi = [[1, 2], [1, 2, 3], [1, 2, 3, 4]];
var product = multi.map(arr => arr.reduce((a, b) => a * b));
console.log(product); // prints [2, 6, 24]
This is the one-liner version of your code.
Array.map transforms an array of elements of type X into another array of elements of type X or anything of the same size.
Array.reduce takes two consecutive elements of an array and by a function called reducer (in this case, (a, b) => a * b), collapse it into a single value.
The above definitions are not accurate but I think they are understandable.