I have the same function repeating over and over again. I'd like to combine it into one so that I can call it without having to write long code.
totalV
.filter((nan) => nan)
.reduce((a, b) => a + b, 0)
.toFixed(2)
Basically, I want to save it into a const or something.. and then call it whenever needed I tried to do something like this:
const Vol =
.filter((nan) => nan)
.reduce((a, b) => a + b, 0)
.toFixed(2)
But unfortunately I wasn't able to do so, because it's asking for "expression" or array to do this funciton on ( something before EXPRESSION.filter.reduce )
EDIT: MORE INFO
{
totalV.filter((nan) => nan)
.reduce((a, b) => a + b, 0)
.toFixed(2) == 0.0
? 0
:
totalV.filter((nan) => nan)
.reduce((a, b) => a + b, 0)
.toFixed(2)}
So I have this conditional render that I'm writing in a few spots.. however totalV can change, but the rest of the code is the same.. so I thought to store the code that keeps repeating into a variable or something like
const repeatableCode =
.filter((nan) => nan)
.reduce((a, b) => a + b, 0)
.toFixed(2)
but it refuses to work without an array/object being provided ahead of time
totalVis/could be. It seems you could just extract the logic to a function and call that when needed.const doSomething = array => array.filter().reduce().toFixed();Vol = totalV => totalV.filter((nan) => nan).reduce((a, b) => a + b, 0).toFixed(2)or even older style withfunction(totalV) { return totalV.filter/*... */ }Just make a regular function that takes a regular parameter and use it regularly. No need to try and find some weird way of preserving the method chain to append elsewhereresult = totalV.filter/*... */ ; result ? 0 : resultOr you could even just use a fallback withtotalV.filter/*... */ ?? 0ortotalV.filter/*... */ || 0(depending on what you need When should I use ?? (nullish coalescing) vs || (logical OR)?)