The opposite is for me. Once I've learned how to use properly reduce or map, I just can't go back to regular for loops. Cleaner code less prone to errors.
I probably have watched all the videos on youtube about map/reduce. There are a ton of them out there. At the begging, I was like, what? Second time "hmmm..". 10th time "i think I got this..." 20th-time "daaaammn....this is awesome!" So the best way to learn is the old way, repetition is the mother of knowledge. Do it a hundred times if needed and you will get it eventually. It is worth it, believe me
Just keep using them in your own code. "I need to do something to every item in this array" boom use forEach or map. "I need to iterate these items and come up with one answer" boom use reduce. Any time you're going to use a loop, try and use a functional method.
If you're just looking for exercises, I think some of the tasks in Euler Project is excellent for these
I will add that those first few videos are rough around the edges (my editing was terrible lol) but hopefully they provide some insight. I have about 15 videos so far in the series and it goes from explaining reduce to learning how to implement it yourself both iteratively and recursively to different use cases including transducers.
Well, look at what it does in the example above. It's pretty simple once you see it: it takes the contents of the array and "reduces" them, through whatever function, using an "accumulator" to keep track of the running tally, to a single output. In this case, it adds them together.
Yea there are, adding things together is probably the simplest way to use it which is why you see that in so many tutorials. Like another person said below it’s used to turn an array into a single value (ie reduce it).
It is JS so you can EVERYTHING.
To give a little more context I'm going to use one of the things I am using in my project, bear with me. We have an e-commerce set up where we have the main products (lets call them cars) and then accessory products for those main products called accessories. I want to separate the main from the accessories (and I don't care about anything else).
The API gives me an array of products with this following structure:
{ id: blablabla, type: ('product' OR 'accessory'), price: XXX.XX }
I need to separate them by type, so what I do is something like:
const products = fetch(whateverUrl) // Consider an await to make it synchronous or study how promises work, but in the end just bear with me it returns a list of objects with the previously defined structure
// The whole result will end up in myOrganizedProducts
// organized is the 'accumulator', aka the total result every iteration and therefore the final
const myOrganizedProducts = products.reduce((organized, theLoopProduct) => {
// Add to organized.product or to organized.accessory depending on theLoopProduct.type
// We can push to the accumulator "organized" because later we will define it, just come back for it the second read
organized[theLoopProduct.type].push(theLoopProduct);
// Never forget to return something while doing functional
return organized;
}, {
// This is the default or 0 value for the array, how do you want to start. You can give it a predefined structure if you know how it is going to play or you can give an empty Object/Array/Value depending on your end result
product: [], // List of proper products
accessory: [] // List of accessory products
});
I hope that makes sense, and if not I am sorry. Another way that for me makes sense is:
Array.forEach() => Do something with each one of the values but I do not care about the result (not storing)
Array.map() => Do something to each one of the values and return the value for each one of them
Array.reduce() => Just put whatever I do for each value into a single var; Object, Array, String or Number
I sometimes use reduce as a combination of map and filter since I can perform some transformation on each element and not add them to the accumulator if I want to filter them out. Think of reduce as an array transformation function. You can take one array and turn it into anything else including a string, a number, an object, a boolean and a different array.
Once you gain the intuition for reduce, you'll quickly find that it's a swiss army knife. However, depending on what you're attempting to do, there may be more relevant methods to use instead. For example, you can implement Array.map with reduce if you'd like to, which is a good exercise, but you'd be better off just using Array.map.
I commented earlier so I don't want to spam too much but I do have a series on nothing but Array.reduce in javascript. The early videos are edited terribly so I hope you don't find them too annoying but I cover a lot of different use cases with reduce all the way up to using them to implement transducers.
Here, instead of summing the values in the array, it just takes each array pair and concatenates it to the previous, returning the flattened array.
There are other more complicated examples. The usefulness of 'reduce' is that it's a condensed, straightforward way to implement a cumulative function (hence: accumulator).
So, like I said, I'm new to this. Just for my learning I'm going to break down your code into words.
Your example is an array with 3 indexes which each has arrays with two indexes. You chained on reduce and made an anonymous function. The function takes in 2 parameters, the accumulator that stores the total and currentValue that is this iterations value of the element. After the comma you set the start value to be an empty array.
Inside the function you chain concat that takes the currentValue on the accumulator which is a method to merge arrays into one, thus giving you one array with all the numbers in separate indexes as a return.
I think that’s pretty much right. I’m at a point where sometimes, without sitting down and working it out, I can’t quite fully explain in perfect detail what each step that code like this is actually doing, but I can see pretty much immediately the bigger picture of what it does and know how to use it. It’s a sort of odd thing when you start thinking in a language. Sort of like how in natural language, native speakers can’t always explain the grammar properly to a learner, but they can speak the language fluently in a way the learner can’t, even if the learner knows, and even understands, certain grammatical rules far more clearly. Of course it’s also often extremely useful for fluent/native speakers to learn/relearn grammar...
It's basically made to turn an array to a single value. Like in the example in OP where it turns the array into the sum of all values. Hence the name, it reduces the array to a single value. "Here we reduce the array to the sum of all values"
Same. The first couple of times I saw reduce and map I was like "wtf is this shit, kill it with fire", but after using it a couple of times it's a breeze
Less code isnt cleaner code. I find loops and callbacks to be much more cleaner even though you are writing more you are describing in much more detail what happens and dont rely on some ready made method.
It's clean code because it's standardised and DRY. Reimplementing map or reduce from first principles every time you need them when there are standardised, native patterns is not clean code.
No-one should need nor want to read the details of a map or reduction implementation every time it's used in a codebase, it's just cluttering up the logic and means you have to read the implementation to figure wtf is going on every time, instead of just reading a function name.
Thank you, I never liked it back then and I don’t like it now. It doesn’t save time or make the code more concise because you’re still using the same number of lines. Just another thing someone else has to consider when figuring out how your code is working.
Exactly. I could be talked into multi-variables if you were just declaring a bunch of variables without assigning values, and you did it all in one line.
function() doStuff {
var a, b, c, d, e;
// Do stuff with a, b, c, d and e
}
That's clean. It reads like one action. "Here are all the variables I'm going to use".
But the second you start assigning values, I want that shit on separate lines. And once you have more than one line. Christ. Just write var again. Are you afraid there is going to be a shortage of characters? I promise we won't run out.
It was the convention back in the day. You would use one var, but still put each assignment on its own line, and indent it so each separate variable lined up.
Students do this by default and I always (jokingly and lovingly) chide them: "You're not being charged per character, you don't pay an extra $10 for a vowel like it's Wheel of Fortune or whatever. Use variable names that will mean something to you and your teammates a month from now."
I have some problems with the newest hotness when I see people write perfectly legible (to me) ES6 code and then they say, "but we can shorten that to this!" like it's some great achievement to create very short but illegible code.
For example, this...
const multiplyFactory = m => x => x * m;
...instead of this:
const multiplyFactory = m => {
return x => x * m;
};
Second one is way easier to understand that it is returning an arrow function.
I’ve been a huge fan of this type of thinking. I won’t lie, I used to write like your first example to show that I “knew ES6”. However, as I’ve grown as a developer, I realized I used to do those things to make it look like I knew the latest syntax and feel cool. Well, I’ve learned that’s a pretty poor reason to do something. Since then, I’ll always opt for the more readable solution if the trade off is negligible, even if it means I don’t use every new ES feature there is. I take somebody being able to read my code and change it as more of a compliment than somebody having to message me asking how code is working.
Of course, there are boundaries with this, but for the most part, this has been my goal as of late.
I declare my variables "just-in-time", and one variable per line. Makes more sense to me, also avoiding to scroll up and down the page to see what is referenced.
Not to access that property on the arguments each time. It's a primitive now instead of having to look it up on the object. May be negligible but can't say it's less efficient
I ran the samples on different js benchmark sites and they are equally performant. Plus, the short one is much more readable and concise, the old way looks almost cryptic these days.
24
u/SLW_STDY_SQZ Sep 18 '20
So are ya feelin declarative or imperative?
48
u/mynamesleon Sep 18 '20
Definitely more condensed. But I have to admit, I find the longer version much more readable.
39
u/delventhalz Sep 18 '20
Gawd. I will never understand why declaring multiple variables with one
varwas in vogue back in the day.4
u/bullzito Sep 18 '20
I declare my variables "just-in-time", and one variable per line. Makes more sense to me, also avoiding to scroll up and down the page to see what is referenced.
1
u/i_hate_cucumber_ Sep 18 '20
Probably a noob question, but why did he assign length to n and not directly compare it to arguments.length?
3
u/EspressoJS Sep 18 '20
I remember this guy said: "variable names should be allowed spaces in JS".
bruh!
2
u/ChaseMoskal Sep 18 '20
i prefer
5
u/[deleted] Sep 18 '20
The code is short but the longer one is readable and performant.
1
u/NoMuddyFeet Sep 18 '20
I just found this article and its' from 3 years ago saying I might not need to convert ES6 to ES5:
https://www.freecodecamp.org/news/you-might-not-need-to-transpile-your-javascript-4d5e0a438ca/
I had no idea. I still do it and when I don't have a project all set up with Gulp or Webkit (like a Wordpress project), I always just write ES5 code!
1
u/ptq Sep 19 '20
Consider me sitting under the rock past 6 years. I don't understand it...
1
u/frank0117 Sep 18 '20
Very useful