Estoy tratando de escribir una función que filtrará una matriz SIN usar la función .filter . Aquí está la función tal como la he escrito hasta ahora;
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; } Las funciones utilizadas como fn son;
function isOdd(x) { return x % 2 === 1; } function alwaysTrue(x) { return true; } function alwaysFalse(x) { return false; } La función actualmente funciona con la función alwaysFalse , pero no con las otras dos. ¿Dónde me estoy equivocando?
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)); // []Está comprobando fn(i) , donde i es el índice del bucle for. Debería verificar fn(ray[i]) , o el valor de la matriz en el índice dado. Lo mismo ocurre con el empuje: debe presionar ray[i] , no 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));Estás presionando el índice, no el elemento.
filterArray.push(i); // should be filterArray.push(ray[i]);También estás llamando a la función en el índice, no al elemento.
if (fn(i) === true) { // should be if (fn(ray[i]) === true) {Aparte de eso, su código está bien.
Puede recorrer fácilmente la matriz usando for...of y empujar el elemento a una nueva matriz.
Nota: Las funciones de devolución de llamada del filtro deben devolver verdadero si se cumple una condición.
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));