Q:

Grouping data from array

I have an array with different objects where each object is an order. 
Looks like this:
array = [
    {
    doc : {
      date: "2017-03-06T16:48:23.080Z",
      products:[
        {
          product: "Product 1",
          number: 3
        },
        {
          product: "Product 2",
          number: 2
        }
      ]
    }
  },
  {
    doc : {
      date: "2017-03-07T16:48:23.080Z",
      products:[
        {
          product: "Product 2",
          number: 10
        },
        {
          product: "Product 3",
          number: 1
        }
      ]
    }
  }
]

I want to be able to take this data and push it into new arrays, where each one has a date property (grouping by date), and a product nested array, which groups the different orders (grouping by product).  Like this:
array = [
    {
       date: 'Date X',
       products: [
         {
          product: 'product 1',
          units: 3
         },
         {
          product: 'product 2',
          units: 2
         }
      ]    
    },
    {
       date: 'Date Y',
       products: [
         {
          product: 'product 2',
          units: 10
         },
         {
          product: 'product 3',
          units: 1
         }

      ]
    }
]

How would you approach this?  I've tried with Lodash trying to reuse some old code with no luck so far.  Could it be done with a forEach? 

A:

Solution using lodash and ES6:
// Remove unnecesary .doc properties
let arrayWithoutDoc = _.map(array, el => el.doc);

// Group by dates to single object
let grouped = _.groupBy(arrayWithoutDoc, el => el.date);

// Convert object to requested format
let result = _.map(grouped, (value, date) => ({
    date: date,
    products: sumProductsUnits(
        _.flatMap(value, el => el.products)
    )
}));

// Function for grouping unique products with sum of units
function sumProductsUnits(products) {
    var productGroups = _.groupBy(products, productObj => productObj.product);

    return _.map(productGroups, (productGroup, productName) => ({
        product: productName,
        units: productGroup.reduce((sum, val) => sum + val.number, 0)
    }))
}

I assumed, that units equals number in orignal object. 
result contains:
[
   {
      "date":"2017-03-06T16:48:23.080Z",
      "products":[
         {
            "product":"Product 1",
            "units":3
         },
         {
            "product":"Product 2",
            "units":2
         }
      ]
   },
   {
      "date":"2017-03-07T16:48:23.080Z",
      "products":[
         {
            "product":"Product 2",
            "units":10
         },
         {
            "product":"Product 3",
            "units":1
         }
      ]
   }
]

