I'm having some issues on how to read arrays.
console.log(arr[i][j]); -- Can someone explain how the i and j fit into this. I'm printing the array i and j to the console, correct?
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
var i = 0;
var j = 0;
for (i = 0; i < arr.length; i++ ) {
for (j = 0; j < arr[i].length; j++) {
console.log(arr[i][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]]);
You are printing the j-th element of the i-th array to the console.
Related
I wrote a simple nested loop function to multiply all items in an array and output the total value, but each time is I run a loop function my browser either crashes or doesn't stop loading
function multiplyAll(arr){
Let product = 1;
for(let i = 0; i <
arr.length; i++){
for(let j = 0; j <
arr[i].length; j *= product);
}
return product;
}
multiplyAll([[1], [2], [3]]);
You are creating an infinite loop here because of
for (let j = 0; j < arr[i].length; j *= product);
Here, j is always 0.
If you want to multiply all the nested value then you should do as:
function multiplyAll(arr) {
let product = 1;
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; ++j)
product *= arr[i][j];
}
return product;
}
console.log(multiplyAll([[1], [2], [3]]));
If you just want to multiple all the nested value then you can simply do as:
function multiplyAll(arr) {
return arr.flat().reduce((acc, curr) => acc * curr, 1);
// If you want to get numbers at any depth then you can flat at any level
// using Infinity as
// return arr.flat(Infinity).reduce((acc, curr) => acc * curr, 1);
}
console.log(multiplyAll([[1], [2], [3]]));
Well, it looks like you have multiple issues, two of them are already as following:
In line 2 you wrote once Let with a big letter at the beginning.
Your second array needs an {} otherwise it will error out
Can you please explain to me j*= product? Can you maybe include a few examples of how you would call this Code and what kind of response you would get? depending on that I will create you a Clear answer!
Description of problem in code. Why it is going on??
var response = JSON.parse(xhr.responseText);
console.log(response[0].conversationUsers.length); //OK, console outputs "2"
for (i = 0; i < response.length; i++) {
for (j = 0; j < response[i].conversationUsers.length; j++) { //Error 'cannot read property', but it has to be interpreted "j = 0; j < 2; j++" and it worked in console.log
...
}
}
UPD. I've added temporary variable and it works.
for (j = 0; j < response[i].conversationUsers.length; j++) //this way doesn't work
var temp = response[i].conversationUsers;
for (j = 0; j < temp.length; j++) //this way works
Question can be closed, but any ideas why so?
You are using console.log() for only the first object in that array. I suggest you try:
var response = JSON.parse(xhr.responseText);
for (i = 0; i < response.length; i++) {
console.log(response[i].conversationUsers); // should be an array
for (j = 0; j < response[i].conversationUsers.length; j++) {
...
}
}
If you get any undefined in your console, while doing this, you have identified your problem.
The thing is that for the first element in the array response[0].conversationUsers has a value that is an array. That might not be true for every element in that array and therefore some of those elements might not have a length property.
You are trying to iterate inside length property. Try to remove length. Like this
var response = JSON.parse(xhr.responseText);
console.log(response[0].conversationUsers.length);
for (i = 0; i < response; i++) {
for (j = 0; j < response[i].conversationUsers; j++) {
...
}
}
As we know, we can omit the initialization inside the for loop :
var i = 0;
for(; i < 10; i++) {
// do Something with i
}
However, i figure out if i omit the initialization inside the nested loop as well:
var i = 0;
var j = 0;
for(; i < 10; i++) {
for(; j < 10; j++) {
// only do Something with j
// outner loop only run once
}
}
Solution :
var i = 0;
var j;
for(; i < 10; i++) {
j = 0;
for(; j < 10; j++) {
// everything is fine!
}
}
Can anyone explain whats going on? I'm newbie in Javascript.
The loop runs multiple times, but your 'j' is already ten after the first run of i, so the second loop no longer runs during the next values of i.
If you would write something like this.
for(; i < 10; i++) {
for(; j < 10; j++) {
console.log("test")
}
console.log("another test")
}
You would see that both messages get printed 10 times.
The reason that your "j" loop, only runs "ten times once", is because you do not set J back to zero after it has run 10 times. So the statement j < 10is true for every loop if iafter the first run.
You could solve this by setting j = 0 inside the first for loop (if you do not want to put it inside the variable initialisation of the second loop.)
for(; i < 10; i++) {
j = 0;
for(; j < 10; j++) {
console.log("test")
}
console.log("another test")
}
Every time i increments, you need to reset j to 0.
If you rewrite your script so that each variable is initialised within the for loop statement itself, then every time i increments, j will be reset to 0.
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
}
}
I've come across writing a piece of code where I wanted to reference the 2D array d2_arr[][] in a loop like so.
for (var i=0; i<d2_arr[i].length; i++) {
//do something
}
Google Script compiler throws an error "cannot read length property from undefined". When I changed [i] for [1], it worked just fine. Could anyone please explain why this is wrong? And a related question: Can a 2D array have a different number of elements in a row? theoretically. An example would be:
[[1,2],[3,4,5],[6,7,8,9],[10,11]]
EDIT. Full code part.
var ids = [];
var j = 0;
for (var i=0; i<d2_arr[i].length; i++){
if (d2_arr[i][2]<=0.05){
ids[j]=d2_arr[i][0];
j++;
}
}
I understood the mistake. Thank you!
You typically need a nested for loop to traverse a 2-D array
var d2_arr = [[1,2],[3,4,5],[6,7,8,9],[10,11]]
for (var i=0; i<d2_arr.length; i++){
for (var j=0; j<d2_arr[i].length; j++){
console.log(d2_arr[i][j] + ' ')
}
}
It is perfectly fine for arrays to be "jagged" and contain uneven sized arrays in the main array.
Here is a fiddle http://jsfiddle.net/7Lr4542s/
Arrays in JS can be of any size and any type. You can combine number and strings in array.
var twoDArray = [[1], ["one", "two"], ["i", "ii", "iii"]];
for(var i = 0; i < twoDArray.length; i++) {
for(var j = 0; j < twoDArray[i].length; j++) {
print(twoDArray[i][j]);
}
}
var threeDArray = [[["1.1.1", "1.1.2"], ["1.2.1", "1.2.2"]], [["1.2.1", "1.2.2"], ["1.2.1", "1.2.2"]], [["2.1.1", "2.1.2"], ["2.2.1", "2.2.2"]], [["2.2.1", "2.2.2"], ["2.2.1", "2.2.2"]]];
for(var i = 0; i < threeDArray.length; i++) {
for(var j = 0; j < threeDArray[i].length; j++) {
for(var k = 0; k < threeDArray[i][j].length; k++) {
print(twoDArray[i][j][k]);
}
}
}
I have a parse background job that contains a simple query.each for one class. This class has 2 Arrays field filled with objects.IDs. Inside this query, for every single object, i need to check if the objects.ID of the first Array are contained in the second Array.
Basically in a simple loop:
var j = 0;
for (var j = 0; j < firstArray.length; j++) {
if(firstArray[j] "isContainedIn" secondArray){
// my custom code
}
}
What i can't figure out is the function to use, if exist..Does javascript have a function like that or i need to make a nested loop to achieve my goal?
EDIT: i worked it out using indexOf but the solution proposed by Shqiptar didn't work so here is the one that actually works:
first Array name = usersEligibleToVote
second Array name = usersThatVoted
for (var j = 0; j < usersEligibleToVote.length; j++) {
if(usersThatVoted.indexOf(usersEligibleToVote[j]) === -1){
console.log("user.id "+usersEligibleToVote[j]+" needs to vote");
} else {
console.log("user.id "+usersEligibleToVote[j]+" has voted");
}
}
var j = 0;
for (var j = 0; j < firstArray.length; j++) {
if(firstArray[j].contains(secondArray))
{
// your custom code here
}
}
And then for checking if an object is the same :
var j = 0;
for (var j = 0; j < firstArray.length; j++) {
if(firstArray[j].indexOf(secondArray) != -1)
{
// your custom code here
}
}
I would process it through a simple jQuery and javascript for loop like so:
var arr1;
var arr2;
var i;
for(i = 0; i < arr1.length; i++) {
if ($.inArray(arr1[i], arr2) {
break; //do things here or what not
}
}