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?
Asked
Active
Viewed 1,810 times
-1

mntblnk
- 77
- 7
-
"Ignore" as in filter them out of the array? – Yannick K Nov 07 '19 at 15:53
-
3Can you define "ignore"? If you just want the control flow to skip over it, a simple `if(num < 0)` would suffice – Klaycon Nov 07 '19 at 15:53
-
https://stackoverflow.com/questions/3571717/javascript-negative-number - please refer to following – Venkatesh Chitluri Nov 07 '19 at 15:55
2 Answers
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