problems with for loop inside another for loop Javacript

4266 views javascript
6

I have problems in going through these two for loops, I need to get the same elements from the first array within the cycle, but the values ??are being repeated. I know that they are repeated depending on the data of the second array.

I tried to make comparisons but I could not get the result I want.

var array = [
{
  grouper: 1
},
{
  grouper: 2
},
{
  grouper: 3
},
];


var array2 = [
{
  value: 1,
  status: 100
},
{
  value: 2,
  status: 100
},
{
  value: 3,
  status: 100
},
{
  value: 4,
  status: 100
},
{
  value: 5,
  status: 100
}
];


for(var i = 0; i<array.length; i++){
   for(var j = 0; j<array2.length; j++){
      console.log(array[i].grouper);
   }
}

This is the result I want:

1
2
3

I need the second array because I'm going to validate with the data from the second array

I do not know if I am doing the process wrong. I hope you can help me.

answered question

If you just want 1, 2, 3, then remove the second for loop. You don't need it.

What is the point of second loop for(var j = 0; j < array2.length; j++)? It's not used in console.log(array[i].grouper).

2 Answers

8

for(var i = 0; i<array.length; i++){
      console.log(array[i].grouper);
}

posted this
3

1, 2, and 3 are only in this array, so the second for loop isn't required:

var array = [
{
  grouper: 1
},
{
  grouper: 2
},
{
  grouper: 3
},
];

The simplest way to write out 1, 2 and 3 is using a for of ... loop:

var array = [
{
  grouper: 1
},
{
  grouper: 2
},
{
  grouper: 3
},
];

for (const item of array) {
  console.log(item.grouper);
}

posted this

Have an answer?

JD

Please login first before posting an answer.