Vinay
Vinay

Reputation: 361

How to group by date in React Native

I am trying to restructure my json response to order by date.

Here is the example Json I have:

"data": [
  {
    "game_id": "728721",
    "game_date": "2016-11-03 20:25:00",
  },
  {
    "game_id": "728722",
    "game_date": "2016-11-06 13:00:00",
  }
]

I want to display sections grouped by date in my listview.

Upvotes: 0

Views: 5806

Answers (2)

Hieu Nguyen
Hieu Nguyen

Reputation: 532

Pure JavaScript method without any library

Since your date time data contain actual string, one strait-forward could be split the string into date and time, then loop through each of item and group them according to date as key. Following is an example just to get the idea (I have not tested but it should work):

var groupData = (data) => {
    let result = []

    for (var d in data) {
        // get date from data
        var date = d.game_date.split(' ');

        // add into new array and use key as the date
        if (!result[date]) {
            result[date] = [d]
        } else {

            // if key already existed, extend into group
            result[date].push(d)
        }
    }

    return result;
}

Upvotes: 1

Adam Clark
Adam Clark

Reputation: 61

this doesnt seem specific to React Native development. maybe try lodash#groupBy

Upvotes: 0

Related Questions