filter negative values in a list of numbers in javascript

To filter negative values in a list of numbers in JavaScript, you can use the filter() method of an array in combination with a conditional statement that checks if the current value is negative. Here's an example code snippet:

index.tsx
const numbers = [1, -2, 3, -4, 5, -6];

const positiveNumbers = numbers.filter(function(number) {
  return number >= 0;
});

console.log(positiveNumbers); // Output: [1, 3, 5]
176 chars
8 lines

In this example, the filter() method is used to create a new array positiveNumbers that only contains the non-negative values from the numbers array. The conditional statement inside the filter() method checks if each number is greater than or equal to zero, and only adds it to the new array if it is.

Alternatively, you can also use an arrow function to make the code shorter:

index.tsx
const numbers = [1, -2, 3, -4, 5, -6];

const positiveNumbers = numbers.filter(number => number >= 0);

console.log(positiveNumbers); // Output: [1, 3, 5]
155 chars
6 lines

gistlibby LogSnag