array iteration
Examples of iterating, mapping, filtering, and reducing arrays.
# Node.js
const array = ["a", "b", "c"];
array.forEach((value, i) => {
console.log(i, value);
});
const mapped = array.map((value) => {
return value.toUpperCase();
});
console.log(mapped);
const filtered = array.filter((value, i) => {
return i % 2 == 0;
});
console.log(filtered);
const reduced = array.reduce((acc, value, i) => {
if (i % 2 == 0) {
acc.push(value.toUpperCase());
}
return acc;
}, []);
console.log(reduced);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Output
0 'a'
1 'b'
2 'c'
[ 'A', 'B', 'C' ]
[ 'a', 'c' ]
[ 'A', 'C' ]
1
2
3
4
5
6
2
3
4
5
6
# Go
package main
import (
"fmt"
"strings"
)
func main() {
array := []string{"a", "b", "c"}
for i, value := range array {
fmt.Println(i, value)
}
mapped := make([]string, len(array))
for i, value := range array {
mapped[i] = strings.ToUpper(value)
}
fmt.Println(mapped)
var filtered []string
for i, value := range array {
if i%2 == 0 {
filtered = append(filtered, value)
}
}
fmt.Println(filtered)
var reduced []string
for i, value := range array {
if i%2 == 0 {
reduced = append(reduced, strings.ToUpper(value))
}
}
fmt.Println(reduced)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Output
0 a
1 b
2 c
[A B C]
[a c]
[A C]
1
2
3
4
5
6
2
3
4
5
6
编辑 (opens new window)
上次更新: 2022/09/30, 11:34:22