Click on text below to jump to specific point in the video


Last time I showed you a basic example of reduce, where we used it to sum the property of a series of objects. It is not limited to reducing a list to a number. It can reduce it to anything - such as an array or an object. I am also going to throw a couple of other higher order functions into the mix.
Start of demo
This is a tab separated file. We are going to turn it into a object literal. The key will be the name. The order items goes in an array. Because we are dealing with a file, we need to import fs namespace from node. To read from file, we use fs.readFileSync.
We get a buffer as output.
We expect the contents of the file. To show the text, it needs a mapping - an encoding table. The most common is utf-8.
Splitting into an array
Splits the string into an array. We see an array of strings. The extra line is due to the final break, we get rid of that by calling trim()
Before we start using reduce on these lines, I would like to convert them into a more manageable object for using a map.
I am going to map every line and split on tab characters. We now have an array of arrays.
Lets reduce it
Reduce takes two arguments - first, a function and then a starting object. Last time we used a number as starting object. This time we will use an object literal.

Reduce needs two arguments - the first one is the object we are constructing.
The second argument is the thing we are iterating, in this case the line. Let me console.log the line out. Lets get rid of console.log and rename to customers. For every customer, we are going to make a property with their name. Now we want to append order id.We want the price, the third part of the line. The quantity is the fourth part of the line.

Use JSON.stringify to print the output nicely.
Let us reuse the existing array to avoid overwriting. We are done. We looked at a more advanced reduce example.We also see some chaining. The chainability is something you will see a lot of in functional programming.
Video outline created using VideoJots