简体   繁体   中英

How to group data by this week and last week records using moment.js

I have an array of objects that have dates properties in it. I wanted to group it by this week's record and last week's record. What's the best way of achieving this using javascript and moment.js. Below is the structure of the dataset.

const obj = [{
   first_name: "Peter",
   last_name: "Hansen",
   date: "2018-01-01"
},
{  first_name: "Jonas",
   last_name:"Da Vinci",
   date: "2018-01-02"
},
{  first_name: "Ohmel",
   last_name: "Reynolds",
   date: "2018-01-03"
},
{  first_name: "Raisa",
   last_name: "Johnson",
   date: "2017-12-25"

},
{
   first_name: "Karen",
   last_name: "Anderson",
   date: "2017-12-26"
},
{
   first_name: "Kristina",
   last_name: "Alvaro",
   date: "2017-12-27"
}]

Expected Output:

This Week

  • Peter Hansen
  • Jonas Da Vinci
  • Ohmel Reynolds

Last Week

  • Raisa Johnson
  • Karen Anderson
  • Kristina Anderson

You can group your array based on the week using array#reduce .

 const arr = [{ first_name: "Peter", last_name: "Hansen", date: "2018-01-01" }, { first_name: "Jonas", last_name:"Da Vinci", date: "2018-01-02" }, { first_name: "Ohmel", last_name: "Reynolds", date: "2018-01-03" }, { first_name: "Raisa", last_name: "Johnson", date: "2017-12-25"}, { first_name: "Karen", last_name: "Anderson", date: "2017-12-26" }, { first_name: "Kristina", last_name: "Alvaro", date: "2017-12-27" }]; var sortedByWeek = arr.reduce((res, {date, first_name, last_name}) => { var startOfWeek = moment(date, 'YYYY-MM-DD').startOf('week').add(1,'days').format('YYYY-MM-DD'); res[startOfWeek] = res[startOfWeek] || []; res[startOfWeek].push(first_name + ' ' + last_name); return res; },{}); console.log(sortedByWeek); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM