Nesting For Loops additional task

Tell us what’s happening:

This code works fine with the requirements of the task , but I was wondering how to make it work if arguments to the function multiplyAll are not nested arrays. Basically to work both ways with nesting and not nested arrays.

Your code so far


function multiplyAll(arr) {
 var product = 1;
 // Only change code below this line
for(var i = 0 ; i < arr.length ; i++){
 for(var j = 0; j < arr[i].length ; j++){
product *=arr[i][j] ;
 }
}
 // Only change code above this line
 return product;
}

// Modify values below to test your code
multiplyAll([[1,2],[3,4],[5,6,7]]);
console.log(multiplyAll([2,2,5]))

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36.

Challenge: Nesting For Loops

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/nesting-for-loops

You could add an if statement to the first loop that checks if the arr[i] element is a number. If so, the product variable is multiplied this number.

If instead the arr[i] element is an array the second loop will execute as normal.

function multiplyAll(arr) {
  var product = 1;
  // Only change code below this line
  for(var i = 0 ; i < arr.length ; i++) {
    if (typeof arr[i] === 'number') {
      product *= arr[i];
    }

    for(var j = 0; j < arr[i].length ; j++){
      product *= arr[i][j];
    }
  }
  // Only change code above this line
  return product;
}

This solution will not work on arrays with greater levels of nesting. To solve that, you would need nested while loops. Alternatively, you could convert the array into a string, and then use a RegExp expression to extract the numbers. Then use the reduce array method to compute the product.

function multiplyAll(arr) {
  var arrStr = JSON.stringify(arr);

  var flattenedArr = arrStr.match(/\d+\.\d+|\d+/g);

  return flattenedArr.reduce(function(a, b) {
    return a * b;
  });
}
1 Like