List Filtering

In this kata you will create a function that takes a list of non-negative integers and strings and returns a new list with the strings filtered out.

Input

Our input is an array of mixed values, strings and numbers

Output

Our return value should be an array.

Explanation

This problem is pretty straight forward. We need to have the strings filtered out and for that we’re going to use Array.prototype.filter().

Filter will iterate over the elements in an array and return the element only if a provided function returns true. When filter is done it will return an new array with the values returned each iteration.

You can use the current element being iterated, the current index, or the original array as parameters when passing a function to filter. In this case we only need to pass each element so that it’s type can be determined because if it’s not a number, then we don’t want to include it in our new array.

With that being said, we’re also going to use the typeof operator. Typeof returns a string the represents what type of the operand. In this case we’re only interested in elements of our array that will return “number”. So let’s do it.

function filter_list(l) {
  // Return a new array with the strings filtered out
  return l.filter(element => typeof element == "number")
}

Another note on filter()

Filter() makes a shallow copy of the array it’s working with. A shallow copy of an object is a copy whose properties share the same references. In the case of this kata it doesn’t really matter because we’re working with primitive values, but if your array was populated with objects then you could run into issues if you didn’t know the difference between a shadow copy and a deep copy, which is where the objects themselves and not just references are copied.

Leave a Reply