I am trying to write a function that will filter an array WITHOUT using the .filter function. Here is the function as I've written it so far;
function filter(ray, fn) {
//The easy way
//let filterArray = ray.filter(fn);
//return filterArray;
let filterArray = [];
for (let i = 0; i < ray.length; ++i) {
if (fn(i) === true) {
filterArray.push(i);
} else {
//do nothing
}
}
return filterArray;
}
The functions used as fn are;
function isOdd(x) {
return x % 2 === 1;
}
function alwaysTrue(x) {
return true;
}
function alwaysFalse(x) {
return false;
}
The function currently works with the alwaysFalse function, but not the other two. Where am I going wrong?
function filter(ray, fn) {
//The easy way
//let filterArray = ray.filter(fn);
//return filterArray;
let filterArray = [];
for (let i = 0; i < ray.length; ++i) {
if (fn(i) === true) {
filterArray.push(i);
} else {
//do nothing
}
}
return filterArray;
}
function isOdd(x) {
return x % 2 === 1;
}
function alwaysTrue(x) {
return true;
}
function alwaysFalse(x) {
return false;
}
console.log(filter([1,2,3,4], isOdd)); // [1,3]
console.log(filter([1,2,3,4], alwaysFalse)); // []