Wut, arr.reduce() is used like a thousand times in our codebase for much more complicated shit than summing some numbers . Pretty fair and reasonable question there for summing an array. And I’m saying that as someone who hates live coding.
Reducers are a tool in state management and not the same things as an array reduce. The latter is a function that is called for each element in the array to reduce it to a single value. The former is a function that accepts a state object and returns a new one.
They're conceptually the same, however, that's why reducers are called reducers.
The callback (reducer) is a function that accepts an accumulator (state object) and a value from an array (update message), then uses those inputs in some way to return a new accumulator (state object). The return value is then used as the input to the next iteration with the next array value (update message).
It's a pattern from functional programming to model state management as a reduce operation on an infinite series of updates.
Why focus on the reduce example? You can just as well do this with for loops, and the way you'd write this function with a for loop is a very basic and common way of making a sum of something.
Either way no developer should have any issue writing the sum function in OP's post. If you need to look that up as a paid developer, I'm sorry to say that you're in the wrong business.
I doubt they'd care if you did a for loop either (though I'd expect a follow-up question to make sure I understood closures and higher-order programming).
I've rarely used it in 10+ years because I don't often work with numbers. I will remember what it does for the next 20 minutes and then that knowledge will disappear into the black hole that is my brain.
reduce is used for more than just numbers, you can use it to construct anything. It's basically the functional programming equivalent of a (generalized) for loop (although usually you'd use something more specific like map/flatMap/filter).
Any time you want an array item to turn into on item that combines them, this is probably worth considering.
Let's do some examples with the classic person object (here's a TS definition). All of these could be done with a for loop, but aren't possible with the more popular .filter() or .map() functions.
interface Person {
firstName: string
lastName: string
age: number
address: string
}
Let's group everyone by last name. Note that acc is short for accumulator and is a fairly popular convention that represents whatever state you are saving between iterations.
const peopleByLastName = people.reduce(
(acc: {[key: string: Person[]}, person: Person) => {
//create the person array if it doesn't exist
if (!acc[person.lastName]) acc[person.lastName] = []
//add a person to the list
acc[person.lastName].push(person)
//return the list so we can use it again
return acc
}, {})
Here's a more complex example of finding the person/people with the longest name.
// get the length of the person's name.
const nameLength = (person: Person): number =>
person.firstName.length + person.lastName.length
const longestNames = people.reduce((acc, person: Person) => {
const length = nameLength(person)
if (length > acc.length) {
acc.person = [person]
} else if (length === acc.length) {
acc.person.push(person)
}
return acc
}, {length: 0, person: []}).person
Here's a max function that works on objects rather than just an array of numbers. This is a very classic example of reducing across a list.
function max<T>(fn: (items: <T>[]) => number, list) =>
list.reduce((acc, item:<T>) => Math.max(fn(item), acc))
let oldest = max<Person>(person => person.age, people)
Another classic example is counting how many items match. You could do this with a .filter(), but you would wind up creating a whole new list just to find out how many while this just creates a single number.
If it's of any help, it doesn't have to be used for numbers. Have you had times where you push items into an array when looping over something? Well you can use reduce instead.
You might be familiar with this pattern of pushing items into an array that is defined outside the scope of the loop.
What do you use it for besides summing numbers? It's perfect for summing, but any other time I've seen a dev use it for something else, it's always been over engineered or just adds complexity and makes code harder to read.
IME, Array.reduce() is one of the most useful array methods, that has the fewest use cases. The question posted above is the perfect use case for it. But I have spoken to FE devs that have a decent amount of experience that may have used it once or twice at most in their careers. And for them, it may not be the first thing that pops into their minds when they see a problem that requires a loop.
I worked at a company that had a coding challenge with a very similar question. It was summing two arrays and returning the higher one. Reduce was the perfect method for that. But from running the interview a few dozen times we realized what I posted above. That it isn't the first thing that comes to mind sometimes. As such, we updated the scoring rubric to not deduct points for interviewees that didn't use reduce in the first pass. Usually during the refactor stage many noticed it, but not all. It is just a pattern that isn't used as often for many FE devs.
43
u/[deleted] Apr 07 '23
Wut, arr.reduce() is used like a thousand times in our codebase for much more complicated shit than summing some numbers . Pretty fair and reasonable question there for summing an array. And I’m saying that as someone who hates live coding.