Reduce Advanced - Part 4 of Functional Programming in JavaScript

Fun Fun Function · Intermediate ·🔧 Backend Engineering ·11y ago

Key Takeaways

This video demonstrates advanced usage of the reduce function in JavaScript, specifically using it to transform a tab-separated file into an object literal, and showcases the composition of higher-order functions like map and reduce.

Full Transcript

[Music] hello we're missing oh the plant I need that for lifestyle well it's Monday again for you guys for me it's Saturday evening and there is a lot of hiking gear behind me this episode will be released automatically to you guys on Monday while I am in a uh canoe traversing the Swedish Wilderness last time I showed you a basic example of reduce where we used it to summarize the property of a series of objects however reduce is not limited to reducing a list to uh a number it can reduce it to anything such as another array or an object and that is what we're going to do today I'm also going to throw a couple of other higher order functions into the mix I've talked previously about how higher order functions compose very well together and I'm going to give you some more examples of this today we're going to jump right into it on the left side of the screen we see data.txt this is a tab separated file so there is tabs here it's tabs oh tabs here here and here and this is just some file that we got out of some old system we having assigned a task we are going to turn it into something that looks a little bit like this so we're going to turn it into a uh object literal and every key in that object is going to be the name so Mark Johnson Mark Johnson here that's the same guy and his uh orders or or order items or whatever goes uh goes in an array so these orders here going to be turned into these so the first uh the first string tab separate string after the the item name is the price of the uh the item and the uh the second integer after the name of the item is going to be the quantity of that item this is our mission we're going to turn this file into this because we're dealing with a file here we need to import the uh FS Nam space from no uh I'm going to use a new requir syntax uh normally you would do something like this but we are going to use modern JavaScript which means that we do this instead so these are the same thing but we're going to use this one now to read from the file we just go fs. read file sync data.txt and it wants no hang on just let me show you what this looks like first also that log out [Music] book right and let's run that as you can see here we're we're getting a buffer uh of bites and that is not quite what we want we expected this to be the contents of the data.txt file and that is just because in in programming and in the computer strings are just a long set of bites it doesn't know how to interpret that into text unless it has some kind of mapping to an encoding TT table a character encoding the most common character encoding is utf8 let's run that again yes we have it let's start by uh I don't know splitting this into uh an [Music] array so split is just a method on the string object that splits the string into an array by uh splitting it using this character here and this is a a line break so if we run this we're going to see an array of straights there's an extra line here I it's because files always tend to have one final line break so we get rid of that by just calling uh trim on the string before we pass it into split and what trim does is that it just removes any line braks or space it at at the end and start of a string so if you run that that little string at the end is now gone before we start using reduce on these lines I would like to uh convert them into a more manageable object first using map I'm going to [Music] map every line and I'm going to split [Music] it on Tab characters see what that looks like okay cool now we have an array of arrays where each array is basically the equivalent of this let's reduce it remember that reduce takes two arguments first takes a function and it also takes a starting object and in the last episode we used a number as a starting object like this but in this case we are going to create an uh object literal so we're going to pass it an object the function that we passed to reduce one's two arguments the first one is the uh object that we are constructing the uh the end goal that we talked about in the beginning of this episode uh and it's uh it's this one and it's going to be passed here on the first Loop and the second argument is the uh the thing that we are iterating in this case it's going to be the line uh and my what I mean by that is these so reduce is going to receive this item on the this array on the first iteration it will receive this array on the second iteration and so on let's run that so far whoops it's returning undefined and that is because output will be whatever reduce Returns on its final iteration so let's return the customer object on it all right it's an empty object that is because we're returning it here and it's empty because we're not doing anything with it yet Just for kicks let me console log the line out on it bam so you'll see here that reduce iterates over the array of arrays that um this map function creates so for each iteration it receives an array another array that is the equivalent of the lines in data. dxt let's get rid of this console log I want to rename this customers cuz we're making a customer's object and for every customer we're going to make a property with their name remember that the first item of the line first part is the name we're going to make that an empty array let's run it okay cool we have have an empty array for Mark Johansson and we have an empty array for Nikita Smith and this is because even though it will get this line then this line then this line it will simply overwrite the mark Johansson property every time and uh the Nikita Smith property every time and now we want to pend the order items so we take this copy it and push to it we push an object so we want name that is the second part of the line and we want the price that is the third part of the line and we want the quantity which is the fourth part of the line and we uh run that H that's a bit hard to read I'm going to teach you a trick now check this out Json do string five null 2 run that again oh much better so what we did here was create a Json string from the uh the output uh with two spaces for indentation we have a bug because only the last item here and the part here is actually being um being added to the array and that is because we are overriding it here so we have to copy this one and just make sure that now we are reusing the existing array if there exists one otherwise we're assigning a new one and we have an output so waffle iron blender oh there's no quantity oh I have a bug find three getting tired right all right and we are done today we looked at a more advanced produ example where instead of using a number we used an object lateral here we also see some chaining going on here good functional code is made up of small functions that do one thing and you just B them all together and that is what we do here we have a trim we have a split we have a map which in turn uses split inside of it uh and we have a reduce the chain ability that you see here is something that you got going to see a lot of if you do functional programming I am going to nibble a bit on the um Jura Superstition whiskey that we are supposed to bring on the canoe trip the uh the other guys won't know that IBL uh because this episode doesn't come out until Monday where not here then so I am on vacation next we week so there won't be an episode next Monday but there will be the Monday after that so please tell me what you think that that episode should be about either comment down below or send me a tweet at mpj me oh and 2 weeks without an episode that's a long time you might forget about me so make sure that you subscribe clicky clicky there there or follow me on Twitter for some of you guys this is good morning and for me this is good night until next time stay [Music] curious

Original Description

💖 Support the show by becoming a Patreon https://www.patreon.com/funfunfunction In this video series, we learn how to do functional programming in JavaScript. In this fourth one, we spend a little bit more time on *reduce*. Playlist of full series is here: https://www.youtube.com/playlist?list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84 How to install and use io.js (for the arrow functions example) http://davidwalsh.name/es6-io You want to follow me on Twitter and Quora: https://twitter.com/mpjme http://www.quora.com/Mattias-Petter-Johansson 💛 Follow on Twitch We record the show live Mondays 7 AM PT https://twitch.tv/funfunfunction 💛 Fun Fun Forum Private discussion forum with other viewers in between shows. https://www.funfunforum.com. Available to patron members, become one at https://www.patreon.com/funfunfunction 💛 mpj on Twitter https://twitter.com/mpjme 💛 CircleCI (Show sponsor) Robust and sleek Docker-based Continuous Integration as a service. I used CircleCI prior to them becoming a sponsor and I love that their free tier is powerful enough for small personal projects, even if they are private. Use this link when you sign up to let them know you came from here: https://circleci.funfunfunction.com 💛 Quokka (Show sponsor) Wonder how MPJ evaluates JavaScript inline his editor. Quokka is the answer - use this link when you buy to let them know you came from here: http://quokka.funfunfunction.com 💛 FUN FUN FUNCTION Since 2015, Fun Fun Function (FFF) is one of the longest running weekly YouTube shows on programming 🏅 thanks to its consistency and quality reaching 200,000+ developers. 🤦‍♂️ The Failing Together concept is what makes FFF unique. Most coding content out there focus on step-by-step tutorials. We think tutorials are too far removed from what everyday development is like. Instead, FFF has created a completely new learning environment where we grow from failure, by solving problems while intensively interacting with a live audience. Tutoria
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Fun Fun Function · Fun Fun Function · 5 of 60

1 Higher-order functions - Part 1 of Functional Programming in JavaScript
Higher-order functions - Part 1 of Functional Programming in JavaScript
Fun Fun Function
2 Map - Part 2 of Functional Programming in JavaScript
Map - Part 2 of Functional Programming in JavaScript
Fun Fun Function
3 Reduce basics - Part 3 of Functional Programming in JavaScript
Reduce basics - Part 3 of Functional Programming in JavaScript
Fun Fun Function
4 Destructuring: What, Why and How - Part 1 of ES6 JavaScript Features
Destructuring: What, Why and How - Part 1 of ES6 JavaScript Features
Fun Fun Function
Reduce Advanced - Part 4 of Functional Programming in JavaScript
Reduce Advanced - Part 4 of Functional Programming in JavaScript
Fun Fun Function
6 Closures - Part 5 of Functional Programming in JavaScript
Closures - Part 5 of Functional Programming in JavaScript
Fun Fun Function
7 Too many tools and frameworks!
Too many tools and frameworks!
Fun Fun Function
8 Currying - Part 6 of Functional Programming in JavaScript
Currying - Part 6 of Functional Programming in JavaScript
Fun Fun Function
9 Recursion - Part 7 of Functional Programming in JavaScript
Recursion - Part 7 of Functional Programming in JavaScript
Fun Fun Function
10 Promises - Part 8 of Functional Programming in JavaScript
Promises - Part 8 of Functional Programming in JavaScript
Fun Fun Function
11 Staying relevant as a programmer
Staying relevant as a programmer
Fun Fun Function
12 Factory Functions in JavaScript
Factory Functions in JavaScript
Fun Fun Function
13 Composition over Inheritance
Composition over Inheritance
Fun Fun Function
14 Software needs to be better - FunFunFunction #1
Software needs to be better - FunFunFunction #1
Fun Fun Function
15 Unit testing: How to get your team started - FunFunFunction #2
Unit testing: How to get your team started - FunFunFunction #2
Fun Fun Function
16 Straight-line code over functions - FunFunFunction #3
Straight-line code over functions - FunFunFunction #3
Fun Fun Function
17 Clojure - FunFunFunction #5
Clojure - FunFunFunction #5
Fun Fun Function
18 The growth stages of a programmer - FunFunFunction #6
The growth stages of a programmer - FunFunFunction #6
Fun Fun Function
19 5 tips to quickly understand a new code base - FunFunFunction #7
5 tips to quickly understand a new code base - FunFunFunction #7
Fun Fun Function
20 Semicolons cannot save you! - FunFunFunction #9
Semicolons cannot save you! - FunFunFunction #9
Fun Fun Function
21 Functors - FunFunFunction #10
Functors - FunFunFunction #10
Fun Fun Function
22 Functors: I was WRONG! - FunFunFunction #11
Functors: I was WRONG! - FunFunFunction #11
Fun Fun Function
23 Questions and Answers - FunFunFunction #12
Questions and Answers - FunFunFunction #12
Fun Fun Function
24 Streams - FunFunFunction #13
Streams - FunFunFunction #13
Fun Fun Function
25 Prototypes in JavaScript - FunFunFunction #16
Prototypes in JavaScript - FunFunFunction #16
Fun Fun Function
26 Fast or Flexible? - FunFunFunction #17
Fast or Flexible? - FunFunFunction #17
Fun Fun Function
27 Coders are herd animals - FunFunFunction #18
Coders are herd animals - FunFunFunction #18
Fun Fun Function
28 Weekend Kubernetes Shenanigans - FunFunFunction #19
Weekend Kubernetes Shenanigans - FunFunFunction #19
Fun Fun Function
29 Monad - FunFunFunction #21
Monad - FunFunFunction #21
Fun Fun Function
30 Moar Weekend Shenanigans - FunFunFunction #23
Moar Weekend Shenanigans - FunFunFunction #23
Fun Fun Function
31 Questions and Answers - FunFunFunction #24
Questions and Answers - FunFunFunction #24
Fun Fun Function
32 Losing motivation - FunFunFunction #25
Losing motivation - FunFunFunction #25
Fun Fun Function
33 LONGEST KUBERNETES SHENANIGANS! - FunFunFunction #26
LONGEST KUBERNETES SHENANIGANS! - FunFunFunction #26
Fun Fun Function
34 Fast code is NOT important - FunFunFunction #27
Fast code is NOT important - FunFunFunction #27
Fun Fun Function
35 Pair Programming a Facebook Messenger Bot - FunFunFunction #28
Pair Programming a Facebook Messenger Bot - FunFunFunction #28
Fun Fun Function
36 Writing unit tests for personal projects? - FunFunFunction #29
Writing unit tests for personal projects? - FunFunFunction #29
Fun Fun Function
37 Let's Code a Pomodoro Button - FunFunFunction #30
Let's Code a Pomodoro Button - FunFunFunction #30
Fun Fun Function
38 What editor do you use? - FunFunFunction #31
What editor do you use? - FunFunFunction #31
Fun Fun Function
39 Arrow functions in JavaScript - What, Why and How - FunFunFunction #32
Arrow functions in JavaScript - What, Why and How - FunFunFunction #32
Fun Fun Function
40 Is Programming Art? - MPJ's Musings - FunFunFunction #33
Is Programming Art? - MPJ's Musings - FunFunFunction #33
Fun Fun Function
41 Generators in JavaScript - What, Why and How - FunFunFunction #34
Generators in JavaScript - What, Why and How - FunFunFunction #34
Fun Fun Function
42 Haskell Basics - FunFunFunction #35
Haskell Basics - FunFunFunction #35
Fun Fun Function
43 Haskell - Baby's first functions - FunFunFunction #36
Haskell - Baby's first functions - FunFunFunction #36
Fun Fun Function
44 Is Big O relevant to you? - Q&A Part 1 - FunFunFunction #37
Is Big O relevant to you? - Q&A Part 1 - FunFunFunction #37
Fun Fun Function
45 How much are you allowed to Google? - Q&A Part 2 - FunFunFunction #38
How much are you allowed to Google? - Q&A Part 2 - FunFunFunction #38
Fun Fun Function
46 Haskell lists - FunFunFunction #39
Haskell lists - FunFunFunction #39
Fun Fun Function
47 var, let and const - What, why and how - ES6 JavaScript Features
var, let and const - What, why and how - ES6 JavaScript Features
Fun Fun Function
48 Why are some programming languages popular? - MPJ's Musings  - FunFunFunction #41
Why are some programming languages popular? - MPJ's Musings - FunFunFunction #41
Fun Fun Function
49 Does a developer need to be nice? - MPJ's Musings - FunFunFunction #42
Does a developer need to be nice? - MPJ's Musings - FunFunFunction #42
Fun Fun Function
50 bind and this - Object Creation in JavaScript P1 - FunFunFunction #43
bind and this - Object Creation in JavaScript P1 - FunFunFunction #43
Fun Fun Function
51 Examples of this and bind - Object Creation in JavaScript P2 -  FunFunFunction #44
Examples of this and bind - Object Creation in JavaScript P2 - FunFunFunction #44
Fun Fun Function
52 Prototype basics - Object Creation in JavaScript P3 - FunFunFunction #46
Prototype basics - Object Creation in JavaScript P3 - FunFunFunction #46
Fun Fun Function
53 Separation of concerns RANT - MPJ's Musings - FunFunFunction #47
Separation of concerns RANT - MPJ's Musings - FunFunFunction #47
Fun Fun Function
54 Cellular Automata - Pair Programming - FunFunFunction #49
Cellular Automata - Pair Programming - FunFunFunction #49
Fun Fun Function
55 The 'new' keyword - Object Creation in JavaScript P4 - FunFunFunction #50
The 'new' keyword - Object Creation in JavaScript P4 - FunFunFunction #50
Fun Fun Function
56 __proto__ vs prototype - Object Creation in JavaScript P5 - FunFunFunction #52
__proto__ vs prototype - Object Creation in JavaScript P5 - FunFunFunction #52
Fun Fun Function
57 Unity game pair programming - Let's code - FunFunFunction #53
Unity game pair programming - Let's code - FunFunFunction #53
Fun Fun Function
58 Throw out your tools - MPJ's Musings - FunFunFunction #54
Throw out your tools - MPJ's Musings - FunFunFunction #54
Fun Fun Function
59 Unit tests vs. Integration tests - MPJ's Musings - FunFunFunction #55
Unit tests vs. Integration tests - MPJ's Musings - FunFunFunction #55
Fun Fun Function
60 Object.create - Object Creation in JavaScript P6 - FunFunFunction #57
Object.create - Object Creation in JavaScript P6 - FunFunFunction #57
Fun Fun Function

This video teaches how to use the reduce function in JavaScript to transform complex data and showcases the power of functional programming in data processing.

Key Takeaways
  1. Import the FS namespace
  2. Read a tab-separated file using fs.readFile
  3. Split the file contents into an array of lines
  4. Use map to split each line into an array of values
  5. Use reduce to transform the array of arrays into an object literal
💡 The reduce function can be used to transform complex data into a desired format, and functional programming principles like composition and higher-order functions can make data processing more efficient and elegant.

Related Reads

📰
how to find in order you want
Learn to implement pagination and filtering in your API calls to retrieve data in the desired order
Dev.to · AlexfamDan
📰
I Started Learning to Code — So I Built My Own Product | SkillLink
Learn how to apply coding skills by building a personal project, accelerating the learning process
Dev.to · Mohamed Tarek
📰
Senior Java Interview Questions Aren’t Hard. The Follow-Ups Are.
Learn how to tackle tough follow-up questions in senior Java interviews to demonstrate your expertise and problem-solving skills
Medium · Programming
📰
Cannot Assign Requested Address in Production: The Connection Failure Most Backend Engineers Blame…
Troubleshoot connection failures in production by checking socket exhaustion and DNS resolution issues
Medium · Programming
Up next
OOP Concepts Explained|Object-Oriented Programming in 60 Seconds| #Shorts | #Simplilearn
Simplilearn
Watch →