JavaScript: Using Underscore.js to handle collections

As I was having to match two collections of objects in a project I was working on I faded out for a minute or two thinking of LINQ and the simplicities of working with collections in C#. I then woke up to horrid, nested for-loops in javascript and realized I had to do something. I googled around and found Underscore.js. This was a simple and fast javascript library for working with collections.

I made an example where I had a list of people and another list with some of the people I had already saved. I wanted a new list with the non-saved people. One way is to create a new list, loop over the list with all the people and within it loop through the list with saved people and compare it and add to the new list.
Or you can do as I did with Underscore.js:

http://jsfiddle.net/maffelu/2jCH9/

var people = [
    {name: "Magnus", "Age": 30},
    {name: "Fadangus", "Age": 29},
    {name: "Laban", "Age": 42},
    {name: "Bintje", "Age": 3}
    ];

var saved = [
   {name: "Fadangus", "Age": 29}
    ];

var result = _.filter(people, function(p)
                      {
                         return _.findWhere(saved, p) === undefined;
                      });

//result: [Object { name="Magnus", Age=30}, Object { name="Laban", Age=42}, Object { name="Bintje", Age=3}]

Leave a Reply