Skip to content

Instantly share code, notes, and snippets.

@samaita
Last active May 23, 2022 04:05
Show Gist options
  • Save samaita/d0be43710c951361288b969d3170caa1 to your computer and use it in GitHub Desktop.
Save samaita/d0be43710c951361288b969d3170caa1 to your computer and use it in GitHub Desktop.
Split an Array into several batch
package main
/*
Playground: https://go.dev/play/p/81iyOZMOeMP
Output:
batch: [1 2 3 4 5 6 7 8 9 10]
batch: [11 12 13]
*/
import "fmt"
func main() {
data := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}
batch := []int{}
batchSize := 10
for index, number := range data {
batch = append(batch, number)
if len(batch) >= batchSize || (len(batch) > 0 && index+1 >= len(data)) {
fmt.Println("batch:", batch)
batch = []int{}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment