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

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

How to Determine if a Column Exists in a DataReader

Silent Renew and the "login_required" Error When Using oidc-client

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4