Using Underscore.js To Split an Array By Groups

While working on a project today, I had to split an array of JSON objects into separate arrays based on one of the object's properties. Underscore.js makes this easy. In the example below, I'm splitting the sections array into a new, multidimensional array called regions.

var regions = _.toArray(_.groupBy(sections, function(section) {
              return section.region;
            }));

Here's an example of the output logged to the browser's console:

Comments

Popular posts from this blog

How To Mock Out Child Components In Unit Tests of Angular 2 Code

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception