-1

I understand that Math.abs is used to convert negative numbers to absolute in JavaScript, but say I want to filter out negative numbers in an array for example, how do I do that? Is there a function for that?

mntblnk
  • 77
  • 7

2 Answers2

4

This should solve your issue [1, 2, -3 , 4, -5].filter(val => val > 0);

Antoni
  • 1,316
  • 2
  • 16
  • 42
2

If you want to eliminate the values, @Antoni 's approach will do.

However, if you want to retain elements but bound the values (also known as clamping) I usually use Math.max(0, number); to set a lower numerical bound - if number is <0, it returns 0.

You can apply this to an array using map:

var array = [1, -2, 3];
array = array.map(number => Math.max(0, number));
//Sets array == [1, 0, 3]

Similarly for an upper bound you can use Math.min(upperLimit, number); and of course you can apply them both for upper and lower bounds:

var array = [1, -2, 3];
const lowerLimit = 0;
const upperLimit = 2;
array = array.map(number => Math.max(lowerLimit, Math.min(upperLimit, number)));
//Sets array == [1, 0, 2]
O Couch
  • 54
  • 4