array iteration


Examples of iterating, mapping, filtering, and reducing arrays.

Node.js

  1. const array = ['a', 'b', 'c']
  2. array.forEach((value, i) => {
  3. console.log(i, value)
  4. })
  5. const mapped = array.map(value => {
  6. return value.toUpperCase()
  7. })
  8. console.log(mapped)
  9. const filtered = array.filter((value, i) => {
  10. return i % 2 == 0
  11. })
  12. console.log(filtered)
  13. const reduced = array.reduce((acc, value, i) => {
  14. if (i % 2 == 0) {
  15. acc.push(value.toUpperCase())
  16. }
  17. return acc
  18. }, [])
  19. console.log(reduced)

Output

  1. 0 'a'
  2. 1 'b'
  3. 2 'c'
  4. [ 'A', 'B', 'C' ]
  5. [ 'a', 'c' ]
  6. [ 'A', 'C' ]

Go

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func main() {
  7. array := []string{"a", "b", "c"}
  8. for i, value := range array {
  9. fmt.Println(i, value)
  10. }
  11. mapped := make([]string, len(array))
  12. for i, value := range array {
  13. mapped[i] = strings.ToUpper(value)
  14. }
  15. fmt.Println(mapped)
  16. var filtered []string
  17. for i, value := range array {
  18. if i%2 == 0 {
  19. filtered = append(filtered, value)
  20. }
  21. }
  22. fmt.Println(filtered)
  23. var reduced []string
  24. for i, value := range array {
  25. if i%2 == 0 {
  26. reduced = append(reduced, strings.ToUpper(value))
  27. }
  28. }
  29. fmt.Println(reduced)
  30. }

Output

  1. 0 a
  2. 1 b
  3. 2 c
  4. [A B C]
  5. [a c]
  6. [A C]