Sort an array in Golang code example
Example 1: Sort an array in Go
s := []int{4, 2, 3, 1}
sort.Ints(s)
fmt.Println(s)
Example 2: golang custom sort
type Person struct {
Name string
Age int
}
type ByAge []Person
func (a ByAge) Len() int { return len(a) }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func main() {
family := []Person{
{"Alice", 23},
{"Eve", 2},
{"Bob", 25},
}
sort.Sort(ByAge(family))
fmt.Println(family)
}
Example 3: sort array of objects in ascending order in js
homes.sort(function(a, b) {
return parseFloat(a.price) - parseFloat(b.price);
});
Example 4: sort list in python
List_name.sort()
This will sort the given list in ascending order.