By displaying this forEach in the console, which extracts the property "monto_gasto" from an array of objects in the firebase database. (In this way)
something.subscribe(res => {
this.ingresos = res;
this.ingresos.forEach(ingreso => {
this.ingresos2.push(ingreso.monto_ingreso);
console.log(this.ingresos2);
});
});
In the Chrome console a new ladder array is created, like so:
[20]
(2) [20, 10]
(3) [20, 10, 241]
(4) [20, 10, 241, 10]
The strange thing is that when displaying any array if all the correct values appear, I just don't know why they are repeated (The number of arrays created is the same as the number of objects contained in one of these arrays)
Unfolded:
[20]↓
0: 20
1: 10
2: 241
3: 10
length: 4[[Prototype]]: Array(0)
(2) [20, 10]↓
0: 20
1: 10
2: 241
3: 10
length: 4[[Prototype]]: Array(0)
(3) [20, 10, 241]↓
0: 20
1: 10
2: 241
3: 10
length: 4[[Prototype]]: Array(0)
(4) [20, 10, 241, 10]
0: 20
1: 10
2: 241
3: 10
length: 4[[Prototype]]: Array(0)
Someone help me please, I need only one array to come out. Thanks in advance.
CodePudding user response:
something.subscribe(res => {
this.ingresos = res;
this.ingresos.forEach(ingreso => {
this.ingresos2.push(ingreso.monto_ingreso);
console.log(this.ingresos2);
});
});
should be
something.subscribe(res => {
this.ingresos = res;
this.ingresos.forEach(ingreso => {
this.ingresos2.push(ingreso.monto_ingreso);
});
console.log(this.ingresos2);
});
Explanation: In your code every time there is an element in the list "ingresos" you are pushing a value of that to an array "ingresos2" and consoling the array i.e "ingresos2". So in first loop it is adding the value from the first element of "ingresos" to "ingresos2" and consoling "ingresos2" which contains only one value. On second loop it is adding the value of the next element of "ingresos" to "ingresos2" and consoling "ingresos2" which now contains 2 values and this goes on. So moving the console outside the loop will print your "ingresos2" one time with the final value after running all the loops.
Hope this helps. Happy Coding :)
Please mark it as answer if it helps
CodePudding user response:
You are pushing and console outputting the same array every time you push something to it. So you'll get as output a ladder array which is the same array in its different points in time.
By the time you unfold it, it is already a complete array.