Pages

filtre and co 3

const products = [

  {
    "_id": 1,
    "item": "abc",
    "price": 10,
    "quantity": 2,
    "date": "2014-03-01T08:00:00.000Z"
  },
  {
    "_id": 2,
    "item": "jkl",
    "price": 20,
    "quantity": 1,
    "date": "2014-03-01T09:00:00.000Z"
  },
  {
    "_id": 3,
    "item": "xyz",
    "price": 5,
    "quantity": 10,
    "date": "2014-03-15T09:00:00.000Z"
  },
  {
    "_id": 4,
    "item": "xyz",
    "price": 5,
    "quantity": 20,
    "date": "2014-04-04T11:21:39.736Z"
  },
  {
    "_id": 5,
    "item": "abc",
    "price": 10,
    "quantity": 10,
    "date": "2014-04-04T21:23:13.331Z"
  },
  {
    "_id": 6,
    "item": "def",
    "price": 7.5,
    "quantity": 5,
    "date": "2015-06-04T05:08:13.000Z"
  },
  {
    "_id": 7,
    "item": "def",
    "price": 7.5,
    "quantity": 10,
    "date": "2015-09-10T08:43:00.000Z"
  },
  {
    "_id": 8,
    "item": "abc",
    "price": 10,
    "quantity": 5,
    "date": "2016-02-06T20:20:13.000Z"
  }
]

function date(min,max){

  return function( {date} ){
    if (new Date(min) <= new Date(date) && new Date(date) <= new Date(max)) {return true}
    else {return false}
  }


}


const myagg = function(acc, cur)  {
  if (!acc[cur.item]) acc[cur.item] = 0;
  acc[cur.item]+=cur.price*cur.quantity;
  return acc
}

const filtre = products.filter(date('2014-01-01','2015-01-01'))
                       .reduce( myagg,{})

console.log(filtre)

const result = []
for (const [key, value] of Object.entries(filtre)) {
  // console.log(`${key}, ${value}`);
  result.push(
    {
      "_id": key,
      "totalSaleAmount": value
    }
  )
}
console.table(result)