-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday_6.js
150 lines (95 loc) · 2.3 KB
/
day_6.js
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
// Activity 1: Array Creation and Access
// Task 1
let arr = [1,2,3,4,5];
console.log(arr);
/* Output: [ 1, 2, 3, 4, 5 ] */
// Task 2
console.log("First element: ", arr[0]);
console.log("Last element: ", arr[4]);
/* Output:
First element: 1
Last element: 5
*/
// Activity 2: Array Methods (Basic)
// Task 3
arr.push(6);
console.log("After adding 6 at end - ", arr);
/* Output: After adding 6 at end - [ 1, 2, 3, 4, 5, 6 ] */
// Task 4
arr.pop();
console.log("After removing last element - ", arr);
/* Output: After removing last element - [ 1, 2, 3, 4, 5 ] */
// Task 5
arr.shift();
console.log("After removing first element - ", arr);
/* Output: After removing first element - [ 2, 3, 4, 5 ] */
// Task 6
arr.unshift(1);
console.log("After adding 1 at front - ", arr);
/* Output: After adding 1 at front - [ 1, 2, 3, 4, 5 ] */
// Activity 3: Array Methods (Intermediate)
// Task 7
const maparr = arr.map((num) => {
return num*2;
});
console.log("New array using map on arr: ", maparr);
/* Output: New array using map on arr: [ 2, 4, 6, 8, 10 ] */
// Task 8
const filterarr = arr.filter((num) => {
if(num%2 == 0) {
return num;
}
});
console.log("New array using filter on arr: ", filterarr);
/* Output: New array using filter on arr: [ 2, 4 ] */
// Task 9
const value = 0;
const sum = arr.reduce((first, second) => {
return first + second;
});
console.log(sum);
/* Output: 15 */
// Activity 4: Array Iteration
// Task 10
console.log(`<-- Printing arr using for loop -->`)
for (let i = 0; i < arr.length; i++) {
console.log(`Element ${i+1} = `, arr[i]);
}
/* Output:
<-- Printing arr using for loop -->
Element 1 = 1
Element 2 = 2
Element 3 = 3
Element 4 = 4
Element 5 = 5
*/
// Task 11
console.log(`<-- Printing arr using foreach loop -->`);
let i = 1;
arr.forEach(ele => {
console.log(`Element ${i} = `, ele);
i++;
});
/* Output:
<-- Printing arr using foreach loop -->
Element 1 = 1
Element 2 = 2
Element 3 = 3
Element 4 = 4
Element 5 = 5
*/
// Activity 5: Multi-dimensional Arrays
// Task 12
console.log(`<-- Printing 2D arr - matrix -->`)
const matrix = [
[1,2,3],
[4,5,6]
];
console.log(matrix);
/* Output:
<-- Printing 2D arr - matrix -->
[ [ 1, 2, 3 ], [ 4, 5, 6 ] ]
*/
// Task 13
console.log(matrix[1][1]);
/* Output: 5 */