Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

RODRIGO MARTINEZ
RODRIGO MARTINEZ
5,912 Points

"Cannot read property 'filter' of null" error.

So my task is. Given an array of integers. Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers. If the input array is empty or null, return an empty array.

I get error "Cannot read property 'filter' of null"

My code :

function countPositivesSumNegatives(input) {
  let positiveNums = input.filter(number => number > 0);
  let negativeNums = input.filter(number => number < 0);

  let positiveCount = positiveNums.length;
  let negativeSum = negativeNums.reduce( (total, num) => {return total + num}  )

  let result = [positiveCount, negativeSum];


  return result;
}

1 Answer

Steven Parker
Steven Parker
231,172 Points

The last part of the instructions reads "If the input array is empty or null, return an empty array." So it will be necessary to handle the possibility that "input" contains "null" before attempting to access the ".filter" method on it.

RODRIGO MARTINEZ
RODRIGO MARTINEZ
5,912 Points

Thanks a lot MR. Parker. Saved the day again. Solved. You are the real Team Tree house legend.