Hi everyone !
I managed to produce the right code (thanks internet), but i have a few questions about it.
My actual code is multiplying everything that have been input in my function, but can i choose which part of the input is being processed ?
It might be futile but this is for the general knowledge.
Thanks,
**Your code so far**
function multiplyAll(arr) {
let product = 1;
// Only change code below this line
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
product *= arr[i][j];
}
}
// Only change code above this line
return product;
}
multiplyAll([[1, 2], [3, 4], [5, 6, 7]]);
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36
I was wondering :
In the case that we want to return an addition/mutlplication/substraction from an array to display the result.
In this case, the function accept an array.
Let’s say that the function input is the following :
function myfunction([[1, 2], [3, 4], [58, 46,1 7]] [1,2,3]);
Let’s say that i want to multiply [1,2] and [1,2,3]
How can i proceed to choose only the desired arrays ?
I remember that we are able to target specific content from our arrays but can’t figure out the procedure.
There are several ways, but I could be misunderstanding. (I am also learning and get confused sometimes.)
Let’s take a simple example, where we select what we want from the array:
//arr is here a 2D array as well, i.e arr = [[1,2],[3,4],...etc]
function firstAndLast(arr){
return [arr[0], arr[arr.length-1]]
}
Then you could pass it to your function. And using either the same or different operators.
Here is a testable code (paste in browser)
function firstAndLast(arr){
const subArr = [arr[0], arr[arr.length-1]]
return subArr
}
function addAll(arr) {
let sum = 0;
// Only change code below this line
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
sum += arr[i][j];
}
}
// Only change code above this line
return sum;
}
const subArr = firstAndLast([[1, 2], [3, 4], [5, 6, 7]])
console.log(addAll(subArr));
It has some bugs, you may fix it !
Now, you can think of a function called “select” where the user tells which subarrays it wants, for example function select(arr){} and user can pass select(1,2,3) and that selects those subarrays, and then calls the next function.
(hope this poor explanation makes some sense). Basically make my snippet more general.
Depending on what specific task would be, also can parameterize indices and deal with subarrays with according indices:
function arraysToAdd(arr, idx1, idx2){
return [arr[idx1], arr[idx2]];
}
function addAll(arr) {
let sum = 0;
// Only change code below this line
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
sum += arr[i][j];
}
}
// Only change code above this line
return sum;
}
const subArr = arraysToAdd([[1, 2], [3, 4], [5, 6, 7]], 0, 1)
console.log(addAll(subArr));