¿No se recomienda esta forma de reducir una matriz (contar ocurrencias)? Quiero decir, ¿modificar el acumulador es quizás malo?
function countOccurrencesReduceOwn(array, searchElement) //seems to work but is maybe not recommended ? { const count = array.reduce((accumulator, currentValue) => { if(currentValue === searchElement) { accumulator++; //do not do this? } return accumulator; }, 0); return count; }Otro similar es el siguiente código que no funciona. Está destinado a obtener el valor más grande de la matriz.
function getMaxReduceOwn(array) //does not work { if(array.length<=0) { return undefined; } const largest = array.reduce((largest, currentValue) => { if(currentValue > largest) { largest =currentValue; //do not do this? } return largest; }, array[0]); }Sí, esto es inusual. Además de "modificar parámetros", reduce proviene de la programación funcional donde se desprecian las variables mutables. Debería simplemente devolver un nuevo valor:
const count = array.reduce((accumulator, currentValue) => { if (currentValue === searchElement) return accumulator + 1; else return accumulator; }, 0); const largest = array.reduce((largest, currentValue) => { if (currentValue > largest) return currentValue; else return largest; }); Si tuviera que reasignar la variable del acumulador, no hay ninguna razón para usar el método de reduce en absoluto, simplemente podría escribir un bucle for normal con el mismo efecto, que sería más corto y más idiomático que el inusual reduce :
let count = 0; for (const currentValue of array) { if(currentValue === searchElement) { count++; } } return count; if (array.length <= 0) { return undefined; } let largest = array[0]; for (const currentValue of array.slice(1)) { if (currentValue > largest) { largest = currentValue; } } return largest;