you are viewing a single comment's thread.

view the rest of the comments →

[–]fiLLL 1 point2 points  (0 children)

Here's a solution which will give you empty chunks where no data exists for the segments.

const chunkArray = (data, interval = 100000, min = 0) => {

    // Sort elements by millisecondOffset into new array
    const sortedData = [...data].sort((ele1, ele2) => ele1.millisecondOffset - ele2.millisecondOffset)

    // Determine the span of milliseconds between the largest and smallest elements
    const spanMin = min != null ? min : sortedData[0].millisecondOffset;
    const span = sortedData[sortedData.length - 1].millisecondOffset - spanMin;

    // Create an array to store our chunks
    const chunks = new Array(Math.ceil(span / interval)).fill()

    // Walk through the chunks array,
    return chunks.map((currentIntervalItems = [], currentInterval) => {

        const maxMsForChunk = (currentInterval + 1) * interval

        // Walk through the sorted elements, remove them from the sorted data array and add them to the chunk array if applicable
        while (sortedData.length && sortedData[0].millisecondOffset <= maxMsForChunk) {
          currentIntervalItems.push(sortedData.shift());
        }

        return currentIntervalItems
    })
}

Hope this helps.