Filter Out Strings from an Array
As always, we'll start by defining the function:
function filterArray(mixedArray) {}
Inside this function, we need to filter out strings and keep only the non-negative integers. To accomplish this, we'll use the filter
method.
The filter
method allows us to iterate over each element in the mixedArray
and keep only those that meet our specified condition.
The filter
method takes a function that evaluates each element (item
) of the array. This function should return true
if the element should be included in the result, or false
otherwise.
To check if an element is a non-negative integer, we need to ensure the element is of type number
and that it is greater than or equal to 0
.
We'll use the typeof
operator to check if the element is a number and the >= 0
condition to ensure it is non-negative. The initial implementation of filter
will look like this:
function filterArray(mixedArray) { const result = mixedArray.filter(function (item) { return typeof item === "number" && item >= 0; }); }
Finally, we need to return the result
from the function, which will be an array containing only the non-negative integers.
The completed function will look like this:
function filterArray(mixedArray) { const result = mixedArray.filter(function (item) { return typeof item === "number" && item >= 0; }); return result; }