Filter an array of object based on weekly filters and return each week data

You can generate the week for each date and using that week with the year as key, create an array with all the common week data.

let data = [{ id: "0ee1a179-2f87-4f11-916c-1341e3d9bcf3", adspend: 1500, createdAt: "25-02-2019" }, { id: "44b0172a-f9e4-4561-b903-fa6b18ee055c", adspend: 4278, createdAt: "27-02-2019" }, { id: "5b66a486-56ff-41e9-9969-e0d820f8521c", adspend: 3966, createdAt: "27-02-2019"}, { id: "88cb602f-63ef-40c7-a30e-cf9dbfd95cc5", adspend: 47898, createdAt: "28-02-2019" }, { id: "3251d613-4d17-4900-b394-2cd8c34f8bf7", adspend: 1536, createdAt: "28-02-2019" }, { id: "c78dfb97-0e2c-4937-b154-0808a8650f08", adspend: 75317, createdAt:"01-03-2019" }, { id: "2eea6d91-5444-4926-8010-df58e59b930b", adspend: 2194, createdAt: "01-03-2019" }, { id: "631af893-b1f6-4012-800a-df27f387232b", adspend: 670, createdAt: "02-03-2019" }, { id: "44b0172a-f9e4-4561-b903-fa6b18ee055c", adspend: 4278,createdAt: "04-03-2019" }, { id: "5b66a486-56ff-41e9-9969-e0d820f8521c", adspend: 3966, createdAt: "04-03-2019" }, { id: "88cb602f-63ef-40c7-a30e-cf9dbfd95cc5", adspend: 47898, createdAt: "06-03-2019" }, { id: "3251d613-4d17-4900-b394-2cd8c34f8bf7", adspend:1536, createdAt: "06-03-2019" }, { id: "c78dfb97-0e2c-4937-b154-0808a8650f08", adspend: 75317, createdAt: "09-03-2019" }, { id: "2eea6d91-5444-4926-8010-df58e59b930b", adspend: 2194, createdAt: "09-03-2019" }, { id: "631af893-b1f6-4012-800a-df27f387232b",adspend: 670, createdAt: "09-03-2019" }, { id: "022dab43-cc38-451f-bfd9-a012de5a6f9f", adspend: 603, createdAt: "11-03-2019" }, { id: "44b0172a-f9e4-4561-b903-fa6b18ee055c", adspend: 4278, createdAt: "12-03-2019" }, { id: "88cb602f-63ef-40c7-a30e-cf9dbfd95cc5",adspend: 47898, createdAt: "13-03-2019" }, { id: "c78dfb97-0e2c-4937-b154-0808a8650f08", adspend: 75317, createdAt: "13-03-2019" }, { id: "2eea6d91-5444-4926-8010-df58e59b930b", adspend: 2194, createdAt: "14-03-2019" }, { id: "631af893-b1f6-4012-800a-df27f387232b",adspend: 670, createdAt: "14-03-2019" }, ],
    result = Object.values(data.reduce((r,o) => {
      let weekNumber = moment(o.createdAt, "DD-MM-YYYY").isoWeek(),
          key = weekNumber + "_" + o.createdAt.slice(-4);
      r[key] = r[key] || [];
      r[key].push({...o});
      return r;
    },{}));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Leave a Comment