newdeveloper
newdeveloper

Reputation: 1451

React-native: Group data by date and display like agenda items

I want to group the data based on date and show date value and their description as shown below. Idea is to make agenda screen like iPhone calendars.

my Data will look like this:

  const events = [
    { date: "2020-04-19", description: "Meeting", startTime: "11:00", endTime: "12:00" },
    { date: "2020-04-19", description: "Coference", startTime: "18:00", endTime: "19:00" },
    { date: "2020-04-20", description: "Team Coference", startTime: "18:00", endTime: "19:00" },
    { date: "2020-04-21", description: "Happy hour cocktail", },
    { date: "2020-04-22", description: "MEditation Class", },
    { date: "2020-04-24", description: "MEditation Class", },
  ]

Current function:

  function renderEventList() {
  let today = moment().format("YYYY-MM-DD")
  let tomorrow = moment().add(1, 'days').format("YYYY-MM-DD");
   return events.map((d, key) => {
      console.log("data1" , d);
      return ( 
        <View>
          <View>
            <Text>
              {d.date === today ? "Today" : 
              d.date === tomorrow ? "Tomorrow" :
              d.date}
            </Text>
          </View>

          <Text>{d.description}</Text>
        </View>
      )
    })
  }

Current result:

enter image description here

Expected result (I will manage the styling part of it)

enter image description here

Upvotes: 0

Views: 1001

Answers (1)

Raz Chiriac
Raz Chiriac

Reputation: 416

I've put together a CodeSandbox React example using your mock data. You can check it out here.

I wrote a function in there called groupBy which is probably what you're looking for. It functions similar to the lodash groupBy method, which you could use if you're ok with adding lodash to your project.

Btw, here's that groupBy function in action:

const events = [
    { date: "2020-04-19", description: "Meeting", startTime: "11:00", endTime: "12:00" },
    { date: "2020-04-19", description: "Coference", startTime: "18:00", endTime: "19:00" },
    { date: "2020-04-20", description: "Team Coference", startTime: "18:00", endTime: "19:00" },
    { date: "2020-04-21", description: "Happy hour cocktail" },
    { date: "2020-04-22", description: "MEditation Class" },
    { date: "2020-04-24", description: "MEditation Class" },
];

const groupBy = (arr, criteria) =>
    arr.reduce((obj, item) => {
        let key = typeof criteria === "function" ? criteria(item) : item[criteria];
        if (!obj.hasOwnProperty(key)) obj[key] = [];
        obj[key].push(item);
        return obj;
    }, {});
    
const grouped = groupBy(events, "date");

console.log(grouped);
    

Hope this helps,

Cheers! 🍻

Upvotes: 2

Related Questions