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

Roku OS 15.0.4 Breaks HEVC Decoding

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

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

Setting Default Values in an Angular Reactive Form

How to Determine if a Column Exists in a DataReader