Doing some JS practice problems and got stumped at this one. I think I’m on the right track, but I’m a little confused as to what action to put in the { } in the checkAge function.
Question:
"For this problem, we will be re-creating the functionality of the .filter function.
Begin by creating a checkAge function.
It needs to take in an array, loop through it, and return a new array containing all the numbers greater than 18."
My code:
function checkAge(val, i, arr) {
if (arr[i]>18) {
newArr = array.filter();
return newArr;
}
}
That was the entire explanation given.
After doing some digging online I found the same problem with the solution either
function checkAge(arr) {
return arr.filter(age => age > 18)
}
or
function checkAge(arr) { // take in an array
var greaterThan18 = []; // initialize new empty array for the greater than 18 values
for (var i = 0; i < arr.length; i++) { // loop through the given array
if (arr[i] > 18) { // if the element in the array is greater than 18…
greaterThan18.push(arr[i]) // put the element in the new array we created earlier
} // we don’t need to do anything with the other elements
that aren’t over 18, so no ‘else’ needed
} // after the for loop is finished…
return greaterThan18 // we can return the array with the elements that are greater
than 18
}
Arrow Functions and Array Methods are both super new to me, so this explanation was pure gold. That’s for taking a look the problem!