could you please help me to solve this code? I need to sum the numbers. With this code I get only "017, 1, 1311 etc"
const array = [
{ id: 1, numbers: [1,] },
{ id: 2, numbers: [7, 1, 13] },
{ id: 3, numbers: [11, 11, 3, 3] },
{ id: 4, numbers: [4, 22, 8, 4, 6, 2] },
];
let totalResult = 0;
array.forEach(item => {
totalResult = item.numbers;
});
console.log(totalResult);
CodePudding user response:
item.numbers
is an Array i.e: numbers: [7, 1, 13]
.
By doing i.e: totalResult = item.numbers
you're basically concatenating an Array.toString() to a Number.
[1, 2, 3].toString()
will equal "1,2,3"
- then 0 = "1,2,3"
results in "01,2,3"
.
Instead, reduce your array to Number:
const array = [
{id: 1, numbers: [1]},
{id: 2, numbers: [7, 1, 13]},
{id: 3, numbers: [11, 11, 3, 3]},
{id: 4, numbers: [4, 22, 8, 4, 6, 2]},
];
const tot = array.reduce((n, item) => n item.numbers.reduce((n, i) => n i), 0);
console.log(tot); // 96
CodePudding user response:
item
is an object in your forEach loop, so you have to loop through item.numbers
to get the actual number and then add with totalResult
.
const array = [
{ id: 1, numbers: [1] },
{ id: 2, numbers: [7, 1, 13] },
{ id: 3, numbers: [11, 11, 3, 3] },
{ id: 4, numbers: [4, 22, 8, 4, 6, 2] },
];
let totalResult = 0;
array.forEach(item => {
item?.numbers.forEach(num => {
totalResult = num;
})
});
console.log(totalResult);