-1

I have an array with this format:

let array = [{length:0},{length:5},{length:5},{length:10},{length:5}]

let sum = array.filter(x=>x.length).reduce((a,b)=>a.length + b.length, 0)

let count = array.filter(x=>x.length).length

console.log(sum,count,sum/count)

What I need is to filter the values > 0 and calculate an average based on those, but it always gets NaN for sum and consequently for the average I need. I started from this answer here.

Thanks for any suggestion.

thednp
  • 4,401
  • 4
  • 33
  • 45
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce – str Aug 23 '20 at 07:21

3 Answers3

1

Your issue is how the way you use the reduce function.

let array = [
  { length: 0 },
  { length: 5 },
  { length: 5 },
  { length: 10 },
  { length: 5 }
];

let sum = array.filter((x) => x.length).reduce((a, b) => a + b.length, 0);
let count = array.filter((x) => x.length).length;
console.log(sum, count, sum / count);
bertdida
  • 4,988
  • 2
  • 16
  • 22
1

You need to store the filtered items and get the sum by taking the length property. The reson for getting NaN, you take a number and get the property length from a, which does not exists. And while using undefined as value for adding, you get NaN as sum.

Later divide by the length of the filterd array.

let array = [{ length: 0 }, { length: 5 }, { length: 5 }, { length: 10 }, { length: 5 }],
    items = array.filter(x => x.length),
    sum = items.reduce((sum, { length }) => sum + length, 0),
    length = items.length,
    average = sum / length;

console.log(sum, length, average);

An approach by using an object for sum and count and a single loop.

let array = [{ length: 0 }, { length: 5 }, { length: 5 }, { length: 10 }, { length: 5 }],
    { sum, count } = array.reduce(
        (o, { length }) => (o.sum += length, o.count += !!length, o),
        { sum: 0, count: 0 }
    ),
    average = sum / count;

console.log(sum, count, average);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Try this:

const array = [{ length: 0 }, { length: 5 }, { length: 5 }, { length: 10 }, { length: 5 }];
let count = 0;
let sum = 0;
for (const item of array) {
  if (item.length) {
    sum += item.length;
    count++;
  }
}
console.log(sum / count);
Shravan Dhar
  • 1,455
  • 10
  • 18