How to write a JavaScript function that returns all positive integers in an array.

How to write a JavaScript function that returns all positive integers in an array.

The big question is, what is a FUNCTION in JavaScript?🤔

The function contains instructions used to create the output from its input. It's like a cow 🐄 that eats grass 🥦(the input) which its body turns into milk 🥛which a dairy farmer then milks (the output).

On codewars.com I came across a challenge to write a function that returns all the positive integers in an array that contains this item [0, 1, 2, 3, 4, -14, -2].

Step i

I created a function positiveInteger and gave it a parameter number.

function positveInteger(number){
}

Step ii

I created an empty array newArray that would return the output.

function positiveInteger(number){
let newArray = []
}

Step iii

I used an array method for loop to loop through the array of numbers which the input.

function positiveInteger(number){
let newArray = []
for(let i = 0; i < number.length; i++){

}
}

Step iv

we all know that any number greater than zero is a positive number 🤪. So, I wrote a condition statement to check for each iteration value is positive. if true, the value is pushed into the empty array newArray we created in Step ii

function positiveInteger(number){
let newArray = []
for(let i = 0; i < number.length; i++ ){
       if(number[i] >= 0){
       newArray.push(number[i])
     }
  }
 return newArray
}

Finally, I call the function on the console with the input given [0, 1, 2, 3, 4, -14, -2] and return all the positive numbers in the array which would be the output as requested [ 0, 1, 2, 3, 4 ]

function positiveInteger(number){
let newArray = []
for(let i = 0; i < number.length; i++ ){
       if(number[i] >= 0){
       newArray.push(number[i])
     }
  }
 return newArray
}

console.log(positiveInteger([0, 1, 2, 3, 4, -14, -2]) //  [ 0, 1, 2, 3, 4 ]

Conclusion

I was glad and excited about how I was able to solve the challenge with the above steps and blocks of codes within two minutes

If you found this article informative 🧠 don't forget to hit the like button as well as the follow button for more interesting blogs about Javascript.👍🏿