19
loading...
This website collects cookies to deliver better user experience
Array.prototype.reduce
mainly around the fact it's difficult to read. At first I thought it was rubbish and that it wasn't difficult at all. The more I thought about it I realised that I've been writing JavaScript for years. I've led teams and projects, I've also been the guy that people come to for help with their JS. I'm an experienced developer. reduce
was empathy. I'll come back to that. reduce
it took a while for it to stick in my brain, I studied it and practiced it and eventually I had the muscle memory to bend code to my will using reduce.reduce
:// Okay so we're going to do something here
// It takes data as an argument and returns something
function doSomething(data){
// Nice a one liner this should be simple
// So I'm guessing 'data' is an array, I know that reduce is for arrays. (TypeScript helps with this!)
// Wait what is acc? What is curr?
// Nice argument names doofus.
// acc + curr.val, okay so is it concatenating strings?
// Oh theres a second argument to reduce
// *reads MDN docs*
// Oh that's the initial value
// Sweet so it's just calculating a total
// So on first pass acc = 0
// Ahh and then for each element of data we add the elements `val` property
return data.reduce((acc, curr) => acc + curr.val, 0)
}
reduce
, this is the primary example that's given on when to use reduce. reduce
is good for other stuff such as grouping data for a given key or combining map
and filter
in a single iteration:const activeIds = items
.filter((item) => item.active === true)
.map((item) => item.id)
const activeIds = items.reduce((result, item) => {
if(!item.active) return result;
return [...result, item.id]
}, [])
Code is read much more than it is written.
function calculateTotalValue(data){
return data.reduce((result, item) => result + item.val, 0)
}
function calculateTotalValue(data){
let sum = 0;
// This could also easily be a straight up for loop
for(let item of data){
sum += i.val;
}
return sum;
}
filter
+ map
. function reduceData(data){
return data.reduce((acc, curr) => acc + curr.val, 0)
}
function forOfData(data){
let sum = 0;
for(let i of data){
sum += i.val;
}
return sum;
}
function forLoopData(data){
let sum = 0;
for(let i = 0, len = data.length; i < len; i++){
sum += data[i].val;
}
return sum;
}
reduce
when I should reach for a simpler solution. I'm trying to be better.