array sorting


Examples of how to sort an array

Node.js

  1. const stringArray = ['a', 'd', 'z', 'b', 'c', 'y']
  2. const stringArraySortedAsc = stringArray.sort((a, b) => a > b ? 1 : -1)
  3. console.log(stringArraySortedAsc)
  4. const stringArraySortedDesc = stringArray.sort((a, b) => a > b ? -1 : 1)
  5. console.log(stringArraySortedDesc)
  6. const numberArray = [1, 3, 5, 9, 4, 2, 0]
  7. const numberArraySortedAsc = numberArray.sort((a, b) => a - b)
  8. console.log(numberArraySortedAsc)
  9. const numberArraySortedDesc = numberArray.sort((a, b) => b - a)
  10. console.log(numberArraySortedDesc)
  11. const collection = [
  12. {
  13. name: "Li L",
  14. age: 8
  15. },
  16. {
  17. name: "Json C",
  18. age: 3
  19. },
  20. {
  21. name: "Zack W",
  22. age: 15
  23. },
  24. {
  25. name: "Yi M",
  26. age: 2
  27. }
  28. ]
  29. const collectionSortedByAgeAsc = collection.sort((a, b) => a.age - b.age)
  30. console.log(collectionSortedByAgeAsc)
  31. const collectionSortedByAgeDesc = collection.sort((a, b) => b.age - a.age)
  32. console.log(collectionSortedByAgeDesc)

Output

  1. [ 'a', 'b', 'c', 'd', 'y', 'z' ]
  2. [ 'z', 'y', 'd', 'c', 'b', 'a' ]
  3. [ 0, 1, 2, 3, 4, 5, 9 ]
  4. [ 9, 5, 4, 3, 2, 1, 0 ]
  5. [ { name: 'Yi M', age: 2 },
  6. { name: 'Json C', age: 3 },
  7. { name: 'Li L', age: 8 },
  8. { name: 'Zack W', age: 15 } ]
  9. [ { name: 'Zack W', age: 15 },
  10. { name: 'Li L', age: 8 },
  11. { name: 'Json C', age: 3 },
  12. { name: 'Yi M', age: 2 } ]

Go

  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. type Person struct {
  7. Name string
  8. Age int
  9. }
  10. type PersonCollection []Person
  11. func (pc PersonCollection) Len() int {
  12. return len(pc)
  13. }
  14. func (pc PersonCollection) Swap(i, j int) {
  15. pc[i], pc[j] = pc[j], pc[i]
  16. }
  17. func (pc PersonCollection) Less(i, j int) bool {
  18. // asc
  19. return pc[i].Age < pc[j].Age
  20. }
  21. func main() {
  22. intList := []int{1, 3, 5, 9, 4, 2, 0}
  23. // asc
  24. sort.Ints(intList)
  25. fmt.Println(intList)
  26. // desc
  27. sort.Sort(sort.Reverse(sort.IntSlice(intList)))
  28. fmt.Println(intList)
  29. stringList := []string{"a", "d", "z", "b", "c", "y"}
  30. // asc
  31. sort.Strings(stringList)
  32. fmt.Println(stringList)
  33. // desc
  34. sort.Sort(sort.Reverse(sort.StringSlice(stringList)))
  35. fmt.Println(stringList)
  36. collection := []Person{
  37. {"Li L", 8},
  38. {"Json C", 3},
  39. {"Zack W", 15},
  40. {"Yi M", 2},
  41. }
  42. // asc
  43. sort.Sort(PersonCollection(collection))
  44. fmt.Println(collection)
  45. // desc
  46. sort.Sort(sort.Reverse(PersonCollection(collection)))
  47. fmt.Println(collection)
  48. }

Output

  1. [0 1 2 3 4 5 9]
  2. [9 5 4 3 2 1 0]
  3. [a b c d y z]
  4. [z y d c b a]
  5. [{Yi M 2} {Json C 3} {Li L 8} {Zack W 15}]
  6. [{Zack W 15} {Li L 8} {Json C 3} {Yi M 2}]