Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save jmcmaster/a26f522784a44fda4bacab0989ccf444 to your computer and use it in GitHub Desktop.

Select an option

Save jmcmaster/a26f522784a44fda4bacab0989ccf444 to your computer and use it in GitHub Desktop.
Simple algorithm to convert React Native FlatList data to SectionList data
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script>
moment.locale();
const data = [
{
datetime: "2018-01-03T13:07:46+00:00",
name: "breakfast"
},
{
datetime: "2018-01-04T00:02:23+00:00",
name: "dinner"
},
{
datetime: "2018-01-03T17:23:54+00:00",
name: "lunch"
},
{
datetime: "2018-01-02T05:21:38+00:00",
name: "dinner"
},
{
datetime: "2018-01-02T17:12:54+00:00",
name: "lunch"
},
{
datetime: "2018-01-02T06:54:25+00:00",
name: "breakfast"
},
{
datetime: "2018-01-02T10:39:17+00:00",
name: "snack"
},
{
datetime: "2018-01-01T12:41:25+00:00",
name: "dinner"
},
{
datetime: "2017-12-29T18:19:12+00:00",
name: "breakfast"
},
{
datetime: "2017-12-28T03:55:21+00:00",
name: "dinner"
},
{
datetime: "2017-12-28T16:44:32+00:00",
name: "snack"
},
{
datetime: "2017-12-28T01:00:46+00:00",
name: "breakfast"
}
]
// Create key param for each object and format datime to locale
let localeData = data.map((item) => {
item.key = moment(item.datetime).format('YYYY-MM-DD')
return item
});
// Sort data by datetime
localeData.sort((a,b) => {
return moment(b.datetime).unix() - moment(a.datetime).unix()
})
// Reduce data for SectionList
const groupedData = localeData.reduce((accumulator, currentValue, currentIndex, array, key = currentValue.key) => {
const keyObjectPosition = accumulator.findIndex((item) => item.key == key)
if (keyObjectPosition >= 0) {
accumulator[keyObjectPosition].data.push(currentValue)
return accumulator
} else {
return accumulator.concat({ data: [currentValue], key: key })
}
}, [])
console.log(groupedData)
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment