Skip to content

v2.4.0

Compare
Choose a tag to compare
@jedib0t jedib0t released this 22 May 04:16
090b0af

Support sorting tables by any of the columns. The sorting directives can be specified using the Column Name (needs a header row with the Column Names) or the Column Number (1-indexed).

Example:

	tw := table.NewWriter()
	tw.AppendHeader(table.Row{"#", "First Name", "Last Name", "Salary"})
	tw.AppendRows([]table.Row{
		{1, "Arya", "Stark", 3000},
		{11, "Sansa", "Stark", 6000},
		{20, "Jon", "Snow", 2000, "You know nothing, Jon Snow!"},
		{300, "Tyrion", "Lannister", 5000},
	})
	tw.SetStyle(table.StyleLight)
	tw.SortBy([]table.SortBy{
		{Name: "Last Name", Mode: table.Asc},
		{Name: "First Name", Mode: table.Dsc},
		{Number: 4, Mode: table.DscNumeric}, // corresponds to the "Salary" column
	})
	fmt.Println(tw.Render())

results in:

┌─────┬────────────┬───────────┬────────┬─────────────────────────────┐
│   # │ FIRST NAME │ LAST NAME │ SALARY │                             │
├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
│ 300 │ Tyrion     │ Lannister │   5000 │                             │
│  20 │ Jon        │ Snow      │   2000 │ You know nothing, Jon Snow! │
│  11 │ Sansa      │ Stark     │   6000 │                             │
│   1 │ Arya       │ Stark     │   3000 │                             │
└─────┴────────────┴───────────┴────────┴─────────────────────────────┘