Home > Programming > Easy functional programming in JavaScript with Underscore.js — part 2

Easy functional programming in JavaScript with Underscore.js — part 2

July 29th, 2011

In the previous post I showed how good use of Underscore.js‘s map function can substantially increase the quality of your code. This time I’ll explore some other functional collection favourites: reduce, select and all.

Reduce that array over a low heat until thick and creamy

Have you ever had to do something like this?

Basically, this is going through some kind of list of values, calculating a new value from each one and accumulating some kind of answer. It’s a common pattern, and there’s an Underscore function for it! This is exactly what _.reduce was built for:

_.reduce takes a collection of values, a function, and a starting value. In this case, the starting value is 0 because we’re building up a running total of numbers. The function is passed the running total (which starts at 0) and each element of the collection. The return value of the function becomes the next value for the running total. _.reduce doesn’t just need to be used on numbers:

In this case, I’m reducing an array of animal objects into a single string. Of course there are plenty of ways to do the above, but this shows you the flexibility of _.reduce.

Bo Selecta!

Imagine you have an array of strings, but you want a new array of strings that start with a capital letter. You might do that like this:

Now, you won’t be surprised to learn that there’s an Underscore function for doing just that: introducing _.select!

Isn’t that much cleaner? Again, we’re abstracting away the minutiae of selecting elements from a list, and just declaring that we want the elements that start with a capital letter. Simples!

All the single ladies

Sometimes you just want to know a yes or no answer about a collection. For example, are all my ladies single?

Hell yes they are. You can read _.all as “is this statement true about all the elements in my collection?” In the same way, _.any can be read as “is this statement true about any of the elements in my collection?”

What about this?

Here’s a useful little tip. When you’re working with nested functions in an object context, you’ll find that this in the nested function doesn’t refer to the object’s context, but the global context. The standard way to deal with this is a line like that = this; or self = this;. There’s a nicer way to do this with Underscore. Nearly all the functions for working on collections take an optional context argument, which specifies what this will be inside the function. Here’s an example:

Because we’re passing the value of this to _.select, the function passed to _.select is working with the correct this. Otherwise, this.maxAge would be undefined.

Learning more

I’ve only gone into some of the functionality that Underscore offers. The docs are very approachable and clear – I urge you to go and read them.

@SamirTalwar on Twitter recommended that I show the alternative syntax for Underscore, as described in the docs. Basically, instead of doing:

_.map(collection, func);

you can do:


And, coupled with .chain() you can do awesome chaining things like this:

Pretty cool. Anyway, use whichever feels right to you. Enjoy!

Categories: Programming Tags: ,
  1. Rob R
    September 10th, 2012 at 14:19 | #1

    This is a great referential. Thanks for this article.

  2. June 7th, 2013 at 16:22 | #2

    Hi, just wanted to tell you, I loved this blog post. It was inspiring. Keep on posting!

  3. August 4th, 2013 at 22:11 | #3

    Hello there I am so delighted I found your blog, I really found you by error, while I was searching on Digg for something else, Anyhow I am here now and would just like to say many thanks for a incredible post and a all round exciting blog (I also love the theme/design), I don’t have time to go through it all at the moment but I have saved it and also added your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the superb work.

  4. April 19th, 2014 at 08:07 | #4

    Great article.

  5. May 14th, 2014 at 16:32 | #5

    Tom Attea, humorist and creator of has already established six shows produced Off-Broadway. There is room for several opinions, many judgements, and many insights into exactly the same piece of news.

    When performing a big project you need to have detailed discussions together with your writer either on email, telephone (Skype is great for this and freee) and see what input they have. It’s belief that about 90% with the content over a website is a bundle of articles. article hopefully ([http://tiny.cc](http://tiny.cc/c758cx “http://tiny.cc”)) Article writing jobs at home facilitates people to write articles and web contents with respect to any organization. As the outline continues, check the relevant materials available once again to make sure of the availability and sufficiency.

  6. May 14th, 2014 at 18:12 | #6

    Or it might be that your herpes diagnostic visit was below ideal. So Murdoch and his third wife, Wendi Deng’s marital status, as well as their two young daughters living conditions, had rarely seen in media reports.

    This support group can provide you with the benefit of these experience, what works well to produce quitting simpler. Don’t write what you don’t wish to happen, like *I don’t need to mess up at the office. [link](http://bit.ly/1nVvQwj9 “link”) report s not necessary should your child or you do must use these types of services because you aren. When you are looking at discussing your disability in personal statements, be cautious about listing down every one of the obstacles you might have come to face because of your respective disability.

  7. May 16th, 2014 at 06:17 | #7

    No appear your needs are, baby supply rentals on Anna Maria; offer you a wide range of things you need for your baby while vacationing. Determine the Metal Type – As mentioned, most truck bed rails are created using tubular steel.

    No appear your needs are, baby supply rentals on Anna Maria; offer you a wide range of things you need for your baby while vacationing. Determine the Metal Type – As mentioned, most truck bed rails are created using tubular steel.

    Make every make an effort to provide correct citations inside the body of your assignment whenever you employ the ideas of others.

    The main difference is always that during IELTS Writing Task 1 in General training you’ll not need to analyze diagram or table and a lot of figures. [regalo hideaway bed rail instructions](http://Larryrxd.buzznet.com/user/journal/17553635/terrific-potency-super-mantra-gayatri/ “regalo hideaway bed rail instructions”) bed rails for seniors walgreens One the opposite hand you use present tense for your generally assent facts as well as regular events.

    Copyscape, Dupecop, Viper, Duplichecker, Google Alerts, Tineye, Article Checker are some with the most vividly used tools for checking plagiarism for any form of content.

  8. May 17th, 2014 at 16:47 | #8

    I’ve been working with the examples in Functional Javascript, and this post and the previous one (“Part 1″) were helpful as well. Thanks!

  9. May 19th, 2014 at 01:32 | #9

    Consider limiting these to essentially the most important and valuable sites or else you’ll start drowning in emails. One thing you could do to boost your life is pay off your debts.

    There are many ways to access your natural wellbeing which are far more efficient than attempting to ignore your problems and convince yourself you might be happy, ‘No, really’ I AM happy’. Liddell hopes to penetrate the 2016 Summer Olympics and rise above being forced to drop out with the 2009 games due to a very painful hernia. least ([http://tiny.cc/](http://tiny.cc/ef68cx “http://tiny.cc/”)) source Focus about what you need to offer a prospective employer; don’t focus on you.

    When you are doing this back it again by your 100% guarantee showing them they have nothing to loose by buying your products and everything to get.

  10. May 19th, 2014 at 01:35 | #10

    t any serious side effects associated while using vaccine, which ought to be encouraging for men who are worried about adverse reactions. The publisher may limit what might be viewed for free and could charge a membership fee for that reader to look in the entire article.

    This is caused by the fact that in many instances it is not your thinking and ideas that you simply are wanting to convey via your writing.

    If I am portion of a minority on this aspect, why did so many people buy ‘Eats, Shoots & Leaves’ it became Book with the Year. [report](http://tiny.cc/s458cx “report”) here When guests at the hotel check out over a happy note, make certain to offer them a card which has a link for the review page of the site or Tripadvisor profile. These mistakes tend to be spelling mistakes, grammatical mistakes, typographical mistakes or semantic errors.

  11. May 19th, 2014 at 16:44 | #11

    Adipex is one such brand broadly renowned for offering good results. Also there some side effects of this drug and one needs to be cautious about the side effects.

    You alone include the authority for what’s true about your projects, however, you’d like feedback on clarity, tone, etc technical matters as spelling and punctuation. Write about topics which make reference to the present demands and needs of one’s readers. While ([Tr.Im](http://tr.im/59cx7 “Tr.Im”)) gnc ripped vitapak Remember ‘ your online presence must speak in your ‘onlyness. We know that for past 5 years use of Internet & its related resources have become up a lot more than 5 times.

  12. June 7th, 2014 at 13:31 | #12

    Wow, marvelous blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your site is magnificent, as well as the content!

  13. June 12th, 2014 at 09:02 | #13

    motorola cordless phone batteries

  14. June 12th, 2014 at 10:57 | #14

    in cream pie

  15. July 16th, 2014 at 15:16 | #15

    Our recommendation is to restaurant chairs miami florida purchase. This would allow the people interested, and family. So we got to try many new things that you want me to another.

  16. October 5th, 2014 at 02:33 | #16

    WHITTIER Mayor Cathy Warner revealed in the week that she has breast cancer. Warner, Sixty three, made the announcement from Tuesday’s Whittier City Council meeting, indicating she wanted people to listen to it from her rather than like a rumor. “It’s a responsibility as elected to get folks to make sure that our elements know that we have the ability to continue on the public’s business,” the lady said. “I expect to be able to match my responsibilities.” Warner is on the council since 04 2004.

  17. October 5th, 2014 at 02:47 | #17

    Unabhängig davon, wer von der Arbeit nimmt es immer die Situation des Arbeitsplatzes, die sich entlang und der Arbeiter wird von Entwicklungen auf der Grundlage Leistungs links, bis zu einem gewissen Grad.. Jeremy Lin und die Knicks die Mavericks Champion. Zusätzlich im Dezember 2012, russische Unternehmen Gazprom Export und Linde ein Memorandum of Understanding (MOU) vorsieht Zusammenarbeit auf neue Helium Produktionsprojekte gleichzeitig mit der Entwicklung der Ost-Sibirien Gasfelder

  18. October 7th, 2014 at 10:24 | #18

    With the latest study from PEW Research stating that 95% of teens have access to the Internet, 80% of kids have cell phones and 48% have data plans, providing a safe cyber-space should be a priority for all parents. A VPN creates an encrypted connection to a third-party server, and all your Internet traffic is routed through that server. It’s probably some mix of the two, so I have to give him props for not going too far in either direction.

  19. October 7th, 2014 at 10:26 | #19

    However, this scene changed when more programmers became aware of virus programming and started building viruses that manipulated and destroyed data on infected computers. However Yahoo marketing and other pay per click search engines offer some excellent traffic at a more reasonable price. A internet marketing business, in a nutshell, a business that’s designed to run on the internet via a website.

  20. October 7th, 2014 at 12:11 | #20

    The backend part of your company supports these profit centers.

    , it is best to go for affiliate marketing being an initial step into the world of generating impartial income from home.

    By ranking your website on the very first page of search engine results, you are tapping into a huge number of people looking for what exactly you offer.

  21. October 9th, 2014 at 17:45 | #21

    The backend part of your company supports these profit centers. They only want your money and they want as much of it as they can possibly get. It’s probably some mix of the two, so I have to give him props for not going too far in either direction.

  22. October 20th, 2014 at 10:22 | #22

    McDonald tillverkning och köpte mark i centrala Minneapolis nästan ett århundrade sedan. Även om det finns ingen klar anledning till varför alkohol bör orsaka hjärta smärta, det spelar tydligen en roll i bröstet obehag. De har dock kommit flera gånger dagligen (läs hela tiden) för att mata på trä birdfeeders och att dricka och bada i trädgården fågelbad fontän.. Smärtlindring kommer med en varning; bar

  23. October 21st, 2014 at 01:35 | #23

    Vous découvrirez comment configurer mondiale connexion Internet large par PPPoEthernet. Ce rapport est conçu pour les apprenants CCNA, ingénieurs de la communauté, et toute personne qui cherche à faire routeur Linksys norme mis en place. Parmi les biens échangés sont des graines de toutes les différentes sortes, stockés dans des combinaisons sans précédent. En plus de son salaire actuel par modèle de vue, ce qui crée virale notori&

  24. October 23rd, 2014 at 01:56 | #24

    Cette préoccupation est encore plus accentué pour Latterday Saint parents quand nous réfléchissons sur nos responsabilités pour enseigner et guider nos enfants. Sa famille a dit Havens est mort d’une crise cardiaque dans le New Jersey lundi. Si vous le souhaitez, vous pouvez changer vos paramètres de cookies à tout moment mais s’il vous plaît soyez conscient que certaines parties du site ne fonctionneront pas correctement si vous désactivez cookies.If

  25. October 31st, 2014 at 01:18 | #25

    Ik zat altijd achter die jongens op school, dus ik had veel training. Hij in eerste instantie bedoeld om te ontmoeten met een grote groep, dan geregeld op een enkele producent. In feite, Larry en ik schreef aan het einde van onze voorwoord in ons boek, is de enige remedie in de reguliere geneeskunde, dat is uit te breiden in gebruik is, krijgt steeds meer aandacht en onderzoek, en het bieden van levensreddende hoop aan tienduizenden mensen, zelfs als sommige van . We keken naar beide strategie&#

  26. April 2nd, 2015 at 13:13 | #26

    Just wish to say your article is as astounding. The clarity on your publish is just cool and i coild think you’re a professional in this subject. Fine together with your permission allow me to clutch your RSS feed to kerp up to date with coming near near post. Thank you one million and please carry on the rewarding work.

    My page seo Dunstable; [Rosalinda](http://adaptableforesi89928.pen.io/ “Rosalinda”),

Comments are closed.