After attempting to sum all the numeric values within the result[i].quantity
array using +=
or
dataset.quantity = 0 + Number(result[i].quantity);
, I encountered issues where the console.log was returning either NaN
or the value from the last iteration like 6135
instead of the expected 36726
.
What am I missing in this straightforward code block?
other logic here ], function (err, result) {
console.log(result); // <<< see №1
let dataset = [];
for (let i = 0; i < result.length; i++ ) {
dataset.min_abs = Math.min(result[i].min_abs);
dataset.min_1 = Math.min(result[i].min_1);
dataset.min_200 = Math.min(result[i].min_200);
dataset.max_1 = Math.max(result[i].max_1);
dataset.max_200 = Math.max(result[i].max_200);
dataset.max_abs = Math.max(result[i].max_abs);
dataset.quantity += Number(result[i].quantity);
console.log(result[i].quantity) // <<< №2
}
console.log(dataset); // <<< №3
}
);
The result
variable (from #1, MongoDB documents) shows:
[ { _id: 1520538161000,
min_abs: 79500,
min_1: 80000,
min_200: 118000,
avg: 108306.51219512195,
max_1: 120000,
max_200: 124493,
max_abs: 130000,
quantity: 6993 },
{ _id: 1520536841000,
...
quantity: 5993 },
{ _id: 1520532881000,
...
quantity: 5935 },
{ _id: 1520535521000,
...
quantity: 5735 },
{ _id: 1520534201000,
...
max_abs: 130000,
quantity: 5935 },
{ _id: 1520531561000,
...
quantity: 6135 } ]
console.log(result[i].quantity)
displays the following values:
6993
5993
5935
5735
5935
6135
The dataset
variable shows:
[ min_abs: 79500,
min_1: 80000,
min_200: 117999,
max_1: 120000,
max_200: 124493,
max_abs: 130000,
quantity: NaN //or 6135 but not 36726]
Despite trying various approaches, including using .map and .reduce, I still aim to simply sum all the numbers within the array during the current for
loop, but have not been successful.
While I understand why I receive 6135 as the result (the last iteration in the loop), I am puzzled as to why +=
or other constructions are not functioning as expected. This has been a unique challenge for me to tackle.