So if you’re trying to remove numbers greater than 10 from an array:
function tenOrLessOnly(inputArr) {
const outputArr = [];
for (let i =0; i < inputArr.length; i++) {
if (inputArr[i] <= 10) {
outputArr.push(inputArr[i]);
}
}
return outputArr;
}
// Call it like
tenOrLessOnly([1,2,3,11,12])
But you can generalise that by passing in whatever the condition is as a function , so instead of saying “if the array element is less than or equal to ten, put that in the output”, you say “if this function returns true for the array element, put that in the output”:
function filter(inputArr, func) {
const outputArr = [];
for (let i =0; i < inputArr.length; i++) {
if (func(inputArr[i])) {
outputArr.push(inputArr[i]);
}
}
return outputArr;
}
function tenOrLess(num) {
return num <= 10;
}
// Call it like
filter([1,2,3,11,12], tenOrLess)
// Same as
filter([1,2,3,11,12], function(num) {
return tenOrLess(num);
}
// Or
filter([1,2,3,11,12], (num) => tenOrLess(num));
// Or
filter([1,2,3,11,12], (num) => num <= 10);
But JS has a function for arrays that does this, filter
, so instead of manually writing that loop, can just do:
function tenOrLess(num) {
return num <= 10;
}
// Call it like
[1,2,3,11,12].filter(tenOrLess)
// Same as
[1,2,3,11,12].filter(function(num) {
return num <= 10;
});
// Or
[1,2,3,11,12].filter((num) => num <= 10));
So for this challenge, you need to remove falsely values: to be explicit in the code, you can use JS’ Boolean()
function which converts whatever you give it to be true/false (it doesn’t need this function, but the code if you leave it off can be a bit confusing if you don’t quite understand what JS is doing):
function. bouncer(arr) {
return arr.filter(val => Boolean(val));
}
// Same as
function. bouncer(arr) {
return arr.filter(Boolean);
}