-
Notifications
You must be signed in to change notification settings - Fork 0
/
map-red-filter.js
71 lines (51 loc) · 1.9 KB
/
map-red-filter.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
// New Array usage
// avoid usage of for, while, ...
// Toutes les fonctions (map, forEach, reduce, ...) attend une fonction a executer a chaque iteration
// cette fonction recoit en args : (element, index, originalArr)
let arr = [
'foo',
'bar',
'tan',
'arthy',
]
console.log(arr);
// Je ne veux pas de "bar", donc filter the list (return `true` to keep it)
let arr2 = arr.filter(el => el !== 'bar')
// let arr2 = arr.filter(el => { return el !== 'bar' })
// let arr2 = arr.filter(function (el) { return (el !== 'bar') } )
console.log(arr2)
// Map ( tranform an array into another array)
let arr3 = arr2.map((el, idx, originalArr) => `${idx} ${el} : ${originalArr[0]}`);
console.log(arr3);
// Reduce (transform an array into a single element)
/*
let whatToDoEveryTime = function (currentValueAccumulator, currentElementOnArray, arrayIdx, originalArray) {
return something; // Example: "Par une somme : currentValueAccumulator + currentElementOnArray"
}
let notAnArrayAnymore = array.reduce(whatToDoEveryTime, startValue);
*/
// Je veux, une string (plus un array), base sur un array
// Enonce "Je veux use string avec toutes les premieres lettres de chaque mots du tableau"
// Premiere lettre (string is an array of char so el[0], but otherwise use String.substr(start, length) t0 get a part of it)
let str = arr.map(el => el[0]).join('');
console.log(str);
let str2 = '';
for (let i=0; i<arr.length;i++) {
str2 += arr[i][0]; // i idx , arr[i] > el
}
console.log(str2);
// ---- Pas trop une nouvelle fonction ----
let arrforreduce = [
'foo',
'bar',
'tan',
'arthy',
];
let strforreduce = arrforreduce.reduce((acc, element) => `${acc}${element[0]}`, '');
console.log(`str for reduce = ${strforreduce}`);
// Join (create a string with all element and separe them with "something" here: ', ')
let str4 = arr.join(', ');
console.log(str4);
// Fais l'inverse
let arr5 = str4.split(', ');
console.log(arr5);