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. Any advice on where I'm 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)); // []
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You're checking fn(i)
, where i
is the index of the for loop. You should be checking fn(ray[i])
, or the value of the array at the given index. Same goes for the push -- you should push ray[i]
, not i
.
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(ray[i]) === true) {
filterArray.push(ray[i]);
} else {
//do nothing
}
}
return filterArray;
}
function isOdd(x) {
return x % 2 === 1;
}
function alwaysTrue(x) {
return true;
}
function alwaysFalse(x) {
return false;
}
const arr = [1, 2, 3, 4, 5, 6, 7];
console.log(filter(arr, isOdd));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You're pushing the index not the element
filterArray.push(i);
// should be
filterArray.push(ray[i]);
You're also calling the function on the index not the element
if (fn(i) === true) {
// should be
if (fn(ray[i]) === true) {
Other than that your code is a-okay.
CodePudding user response:
You can easily loop through the array using for...of
and push the item into a new array.
Note: The filter callback functions should return true if a condition is met.
function filter(arr, fn) {
const filtered = [];
for(const item of arr){
if(fn(item)) filtered.push(item);
}
return filtered;
}
const isOdd = (x) => x % 2 === 1;
const numbers = [1, 2, 3, 4, 5, 6, 7];
console.log(filter(numbers, isOdd));
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>