Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 19c76db

Browse files
committed
Added REVIEW Week 7 content
1 parent 928309c commit 19c76db

File tree

3 files changed

+193
-6
lines changed

3 files changed

+193
-6
lines changed

Week7/REVIEW.md

Lines changed: 193 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,196 @@
11
# REVIEW JavaScript week 7
22

3+
## Git Workflow
4+
5+
To be provided
6+
7+
## Map, filter, reduce
8+
9+
The array methods **map()**, **filter()** and **reduce()** are best understood by looking at how they could be implemented if we were to write them ourselves. In the next few sections we will present simplified versions of the native implementations. We have prefixed the method names with `my` to distinguish them from the built-in versions.
10+
11+
### Array#map\*
12+
13+
The **map** method returns a new array where each element of the subject array is transformed by a user-supplied transformation (= _mapping_) function.
14+
15+
```js
16+
Array.prototype.myMap = function (mapFn) {
17+
const arr = [];
18+
for (let i = 0; i < this.length; i++) {
19+
arr.push(mapFn(this[i], i, this));
20+
}
21+
return arr;
22+
};
23+
```
24+
25+
<small>\* Array#map is a short-hand notation for Array.prototype.map.</small>
26+
27+
As you can see, the `mapFn` function is called with three arguments:
28+
29+
1. the current array element to be transformed
30+
2. the index of the element (starting with `0`)
31+
3. the subject array itself
32+
33+
As is usual in JavaScript you do not necessarily have to use all the parameters that were passed to the `mapFn` function. In fact, in many cases you will only need the first argument (the current array element).
34+
35+
In the example below we will use the Array#map method to compute the squares of an array of numbers.
36+
37+
```js
38+
const numbers = [3, 5, 2, 7];
39+
const squares = numbers.map(num => num * num);
40+
console.log(squares); // -> [9, 25, 4, 49]
41+
```
42+
43+
### Array#filter
44+
45+
The **filter()** method returns a new array with all elements that pass the test implemented by a user-supplied (predicate\*) function.
46+
47+
```js
48+
Array.prototype.myFilter = function (predicateFn) {
49+
const arr = [];
50+
for (let i = 0; i < this.length; i++) {
51+
if (predicateFn(this[i], i, this)) {
52+
arr.push(this[i]);
53+
}
54+
}
55+
return arr;
56+
};
57+
```
58+
59+
<small>\*A predicate is a function that returns a boolean, whose value depends on its supplied arguments.</small>
60+
61+
Example:
62+
63+
```js
64+
const numbers= [6, 3 , 10, 1];
65+
const evenNumbers = numbers.filter(num => num % 2 === 0);
66+
console.log(evenNumbers); // -> [6, 10]
67+
```
68+
69+
### Array#reduce
70+
71+
Of the three methods **map**, **filter** and **reduce**, the **reduce** method presents the most difficulty for new learners. The _Mozilla Developer Network_ (MDN) web site gives the following definition:
72+
73+
> The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value\*\*.
74+
75+
<small>\*\*Although reference is made to a 'single value', this single value may well be an array or an object, as you will see later in the examples below.</small>
76+
77+
```js
78+
Array.prototype.myReduce = function (reducerFn, initialValue) {
79+
let accumulator = initialValue;
80+
for (let i = 0; i < this.length; i++) {
81+
accumulator = reducerFn(accumulator, this[i], i, this);
82+
}
83+
return accumulator;
84+
};
85+
```
86+
87+
The whole process is visualised in the figure below (the term _bucket_ was used here to represent the accumulator).
88+
89+
![image](assets/reduce-bucket.png)
90+
91+
The **reduce()** method is the most flexible of the map/filter/reduce triplet. In fact, it is possible to rewrite **map()** and **filter** using **reduce()**.
92+
93+
#### Using reduce() to filter
94+
95+
```js
96+
const arr = [6, 3, 10, 1];
97+
const evenNumbers = arr.reduce((acc, elem) => {
98+
if (elem % 2 === 0) {
99+
acc.push(elem);
100+
}
101+
return acc;
102+
}, []);
103+
console.log(evenNumbers); // -> [6, 10]
104+
```
105+
106+
In this example our accumulator is an (initially empty) array. We put elements (in this case integer numbers) in the accumulator only when they are divisible by 2.
107+
108+
#### Using reduce() to map
109+
110+
In this example an array of integer numbers is mapped to an array of their squares.
111+
112+
```js
113+
const arr = [6, 3, 10, 1];
114+
const squares = arr.reduce((acc, elem) => {
115+
acc.push(elem * elem);
116+
return acc;
117+
}, []);
118+
console.log(squares); // -> [36, 9, 100, 1]
119+
```
120+
121+
### Using reduce() to 'group by'
122+
123+
In this example our accumulator is not an array, but an (initially empty) object. It groups the array elements by gender.
124+
125+
```js
126+
const arr = [
127+
{ gender: 'F', name: 'Joyce'},
128+
{ gender: 'M', name: 'Jim' },
129+
{ gender: 'F', name: 'Lucy' },
130+
{ gender: 'M', name: 'Ferdinand' }
131+
];
132+
const groupedNames = arr.myReduce((acc, elem) => {
133+
if (acc[elem.gender]) {
134+
acc[elem.gender].push(elem);
135+
} else {
136+
acc[elem.gender] = [elem];
137+
}
138+
return acc;
139+
}, {});
140+
console.log(groupedNames);
3141
```
4-
This review covers:
5-
• Git Workflow
6-
• Map,
7-
• Reduce
8-
• Filter
9-
```
142+
143+
Result:
144+
145+
```js
146+
{
147+
F: [
148+
{ gender: 'F', name: 'Joyce' },
149+
{ gender: 'F', name: 'Lucy' }
150+
],
151+
M: [
152+
{ gender: 'M', name: 'Jim' },
153+
{ gender: 'M', name: 'Ferdinand' }
154+
]
155+
}
156+
```
157+
158+
### Method chaining
159+
160+
The methods **map()**, **filter()** and **reduce()** each return a new array. This makes it possible to chain these methods and create a 'pipeline' of operations, to be applied in sequence. Let's take the last example, but now filtering out only those array elements for which the name starts with a 'J':
161+
162+
```js
163+
const arr = [
164+
{ gender: 'F', name: 'Joyce' },
165+
{ gender: 'M', name: 'Jim' },
166+
{ gender: 'F', name: 'Lucy' },
167+
{ gender: 'M', name: 'Ferdinand' }
168+
];
169+
const groupedNames = arr
170+
.filter(elem => elem.name.startsWith('J'))
171+
.reduce((acc, elem) => {
172+
if (acc[elem.gender]) {
173+
acc[elem.gender].push(elem);
174+
} else {
175+
acc[elem.gender] = [elem];
176+
}
177+
return acc;
178+
}, {});
179+
console.log(groupedNames);
180+
```
181+
182+
Result:
183+
184+
```js
185+
{
186+
F: [{ gender: 'F', name: 'Joyce' }],
187+
M: [{ gender: 'M', name: 'Jim' }]
188+
}
189+
```
190+
191+
## In summary
192+
193+
![image](assets/map-filter-reduce-emoji.png)
194+
195+
Credit: http://www.globalnerdy.com/2016/06/23/map-filter-and-reduce-explained-using-emoji/
196+
163 KB
Loading

Week7/assets/reduce-bucket.png

38.2 KB
Loading

0 commit comments

Comments
 (0)