Search code examples
javascriptdatetimemomentjslodash

Using Moment to Combine a list of hourly dates by day


I have price/date data in the form of [date, price]

let priceData = [
    [1551052800000, 0.33739737955243454]
    [1551139200000, 0.33628886196814234]
    [1551225600000, 0.12674156277665535]
    [1551312000000, 0.16847247989576378]
    [1557792000000, 0.5650889670671049]
    [1557878400000, 0.6003006017008962]
    [1557964800000, 0.6438789432408669]
    [1558051200000, 0.6684895789112406]
]

I was wondering a clean way to take a list like this using lodash or map or something and combine it according to same dates like...

// the data below may not be accurate, the point here is the structure
let exampleChuckedData = [
    [
            [1551052800000, 0.33739737955243454]
            [1551139200000, 0.33628886196814234]
            [1551225600000, 0.12674156277665535]
            [1551312000000, 0.16847247989576378]
    ]
    [
            [1557792000000, 0.5650889670671049]
            [1557878400000, 0.6003006017008962]
            [1557964800000, 0.6438789432408669]
            [1558051200000, 0.6684895789112406]
    ]
]

// Or more conceptually
// Grouped by same date
let exampleConceptData = [
    [
            ['01/01/2019', 0.33739737955243454]
            ['01/01/2019', 0.33628886196814234]
            ['01/01/2019', 0.12674156277665535]
            ['01/01/2019', 0.16847247989576378]
    ]
    [
            ['01/02/2019', 0.5650889670671049]
            ['01/02/2019', 0.6003006017008962]
            ['01/02/2019', 0.6438789432408669]
            ['01/02/2019', 0.6684895789112406]
    ]
]

I use moment for all my date formatting needs. Maybe there's a way to integrate moment to help with this like with their *.isSame()


Solution

  • You can use _.groupBy(), and in the callback convert each date to a day using moment(date).day(). The convert the groups' object to an array with _.values():

    const priceData = [[1551052800000,0.33739737955243454],[1551139200000,0.33628886196814234],[1551225600000,0.12674156277665535],[1551312000000,0.16847247989576378],[1557792000000,0.5650889670671049],[1557878400000,0.6003006017008962],[1557964800000,0.6438789432408669],[1558051200000,0.6684895789112406]]
    
    const result = _.values(_.groupBy(priceData, ([d]) => moment(d).startOf('day')
    ))
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.14/lodash.js"></script>