arrays


Examples of slicing, copying, appending, and prepending arrays.

Node.js

  1. const array = [1, 2, 3, 4, 5]
  2. console.log(array)
  3. const clone = array.slice(0)
  4. console.log(clone)
  5. const sub = array.slice(2,4)
  6. console.log(sub)
  7. const concatenated = clone.concat([6, 7])
  8. console.log(concatenated)
  9. const prepended = [-2,-1,0].concat(concatenated)
  10. console.log(prepended)

Output

  1. [ 1, 2, 3, 4, 5 ]
  2. [ 1, 2, 3, 4, 5 ]
  3. [ 3, 4 ]
  4. [ 1, 2, 3, 4, 5, 6, 7 ]
  5. [ -2, -1, 0, 1, 2, 3, 4, 5, 6, 7 ]

Go

  1. package main
  2. import "fmt"
  3. func main() {
  4. array := []int{1, 2, 3, 4, 5}
  5. fmt.Println(array)
  6. clone := make([]int, len(array))
  7. copy(clone, array)
  8. fmt.Println(clone)
  9. sub := array[2:4]
  10. fmt.Println(sub)
  11. concatenated := append(array, []int{6, 7}...)
  12. fmt.Println(concatenated)
  13. prepended := append([]int{-2, -1, 0}, concatenated...)
  14. fmt.Println(prepended)
  15. }

Output

  1. [1 2 3 4 5]
  2. [1 2 3 4 5]
  3. [3 4]
  4. [1 2 3 4 5 6 7]
  5. [-2 -1 0 1 2 3 4 5 6 7]