We are going to write a function called getPositives that will accept an array, ar, as an argument.

You are given an array containing both positive and negative numbers. The goal of the function is to output another array containing only the positive numbers found in the input array.

Example:

let numArr = [-5, 10, -3, 12, -9, 5, 90, 0, 1];
getPositives(numArr);

// output: [10,12,5,90,0,1]

There’s not much to explain here. All values that are greater than -1 remain goes into the output array.

There are a couple of ways to write this function but we will focus on one using the filter() method.

What the filter() method does is creates a new array containing all the elements in the array that passes the test within the provided callback function.

The array filters out numbers that don’t pass the test. The test we want the function to check for is if the value passed is greater than -1. All numbers less than 0 won’t go into the array.

We will put this new array into a variable called posArr.

const posArr = ar.filter(num => num > -1);

Our test function within the filter() method is equivalent to writing:

const posArr = ar.filter(function(num){
    return num > -1;
});

Now that we have our array containing nothing but positive numbers, we will return posArr.

return posArr;

Here is the rest of the function:

function getPositives(ar){
    const posArr = ar.filter(num => num > -1);
    return posArr;
}

#javascript #coding #algorithms

JavaScript Algorithm: Return Positive Numbers
7.65 GEEK