-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMapFilterReduceBonus.html
More file actions
491 lines (453 loc) · 20 KB
/
MapFilterReduceBonus.html
File metadata and controls
491 lines (453 loc) · 20 KB
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
// https://java.codeup.com/extra-exercises/javascript/map-filter-reduce/
'use strict';
{
const fruits = ["cantaloupe", "orange", "date", "elderberry", "ugli fruit", "pineapple"];
const customers = [
{
name: "Fred",
age: 58,
occupation: "Police Officer",
noOfPurchases: 4
},
{
name: "Samantha",
age: 54,
occupation: "Teacher",
noOfPurchases: 18
},
{
name: "Charles",
age: 38,
occupation: "Librarian",
noOfPurchases: 9
}
];
const pets = [
{
name: 'Bud',
age: 2,
breed: 'Pug'
},
{
name: 'Gabby',
age: 10,
breed: 'Retriever'
},
{
name: 'Fred',
age: 1,
breed: 'Lab'
},
{
name: 'Bowser',
age: 2,
breed: 'Pug'
}
];
const family = [
{
name: "Pam",
gender: "female",
age: 29,
},
{
name: "Amelie",
gender: "female",
age: 10,
},
{
name: "Justin",
gender: "male",
age: 32,
},
];
// Use map, filter, and reduce to:
// 1 Create an array of the first letters of each fruit
const firstLetterArr = fruits.map(fruit => fruit.charAt(0));
// 2 Create array of user objects based on the customers array of objects (each user object should just have name and age properties)
const userObjArr = customers.map(({name, age}) => ({name, age}));
// 3 Create an array of civil servant customers (teachers and police officers) containing the same properties as the objects on the customers objects
const civilServantCustomers = customers.filter(customer => customer.occupation !== 'Librarian');
const civilServantCustomers1 = customers.filter(({occupation}) => occupation === 'Police Officer' || occupation === 'Teacher');
// 4 Determine the average age of all the customers
const averageAge = customers.reduce((acc, customer) => acc + customer.age, 0) / customers.length;
// 5 Create a function makeSuperPet() that takes in the pets array as input and returns a single pet object with the following shape...
// {
// name: ALL_PET_NAMES_CONCATENATED_INTO_A_SINGLE_STRING,
// age: THE_TOTAL_OF_ALL_PET_AGES,
// breed: THE_FIRST_LETTERS_OF_ALL_PET_BREEDS_CONCATENATATED_INTO_A_SINGLE_STRING
// }
function makeSuperPet(arr) {
const name = arr.reduce((acc, cur) => `${acc}${cur.name.charAt(0)}`, '');
const age = arr.reduce((acc, cur) => acc + cur.age, 0);
const breed = arr.reduce((acc, cur) => `${acc}${cur.breed.charAt(0)}`, '');
return {
name,
age,
breed
};
}
// 6 Create a function that takes in an array of pets and returns an array of the length of first names for pugs only. Your output for the given input should be [3, 6] for 'Bud' and 'Bowser'
function pugNameLength(arr) {
return arr.filter(ele => ele.breed === 'Pug').map(ele => ele.name.length);
}
// 7 Create a function getFemaleFamilyMembers() that when given the family variable as an argument, returns an array of female family member names
function getFemaleFamilyMembers(arr) {
return arr.filter(ele => ele.gender === 'female').map(ele => ele.name);
}
// 8 Create a function makeLongPetString() that when given the variable of pets, returns a string of all property values with dashes separating each property value
function makeLongPetString(arr) {
return arr.reduce((acc, {name, age, breed}) => `${acc}-${name}-${age}-${breed}`, '').slice(1);
}
// 9 Create a function that when given an array of first names, returns an array of the same names with a last name of Smith
// input = ['Sally', 'Fred', 'Steve']
// output = ['Sally Smith', 'Fred Smith', 'Steve']
function lNameSmith(arr) {
return arr.map(ele => `${ele} Smith`);
}
// 10 Create a function that when given an array of numbers, return the sum of the even numbers
function evenNumSum(arr) {
return arr.filter(ele => ele % 2 === 0).reduce((acc, cur) => acc + cur);
}
// 11 Create a function that when given an array of numbers, return the sum of all numbers evenly divisible by 10
function tenDivisibleSum(arr) {
// arr.reduce((acc, cur) => {
// if (cur % 10 === 0) return acc + cur;
// else return acc;
// }, 0)
// arr.reduce((acc, cur) => {
// console.log(acc, cur);
// return cur % 10 === 0 ? acc + cur : acc;
// }, 0)
return arr.reduce((acc, cur) => cur % 10 === 0 ? acc + cur : acc, 0)
}
// 12 Create a function that when given an array of names, return a string of all the first letters of each name
function nameFistLetter(arr) {
return arr.reduce((acc, cur) => `${acc}${cur.charAt(0)}`, '')
}
// 13 Create a function that when given an array of values, returns an array of only the truthy values
function truthyValues(arr) {
return arr.filter(ele => ele);
// arr.filter(ele => !!ele);
// arr.reduce((acc, cur) => cur ? acc.concat(cur) : acc, []);
}
// 14 Create a function that when given an object, returns the property values as an array of elements
function valueArr(obj) {
return Object.values(obj);
}
function valueArr1(obj) {
return Object.keys(obj).map(ele => obj[ele]);
}
// 15 Create a function that when given an object, returns the property names as an array of elements
function propArr(obj) {
return Object.keys(obj);
}
function propArr1(obj) {
let result = [];
for (prop in obj) {
result.push(prop);
}
return result;
}
function propArr2(obj) {
let result = [];
for (let prop in obj) {
result.push(prop);
}
return result;
}
function propArr3(obj) {
let result = [];
for (let key in obj) {
result.push(key);
}
return result;
}
// 16 Create a function that when given three arguments: a min num, a max num, an array of nums will return the array of nums that are only between the min and max values, inclusive
function numArr(minNum, maxNum, arr) {
return arr.filter(ele => ele >= minNum && ele <= maxNum);
}
// 17 Create a function that when given an array of strings, returns an array of objects with properties for the given string value and the length of the string and the string without vowels (not including y)
function newObj(arr) {
return arr.map(ele => {
let newObj = {};
newObj.value = ele;
newObj.length = ele.length;
newObj.withoutVowels = ele.replace(/(a|e|i|o|u)/gi, '');
return newObj;
})
}
function newObj1(arr) {
return arr.reduce((acc, ele) => {
acc.push({
value: ele,
length: ele.length,
withoutVowels: ele.replace(/(a|e|i|o|u)/gi, '')
});
return acc;
}, [])
}
function newObj2(arr) {
return arr.reduce((acc, ele) => {
return acc.concat({
value: ele,
length: ele.length,
withoutVowels: ele.replace(/(a|e|i|o|u)/gi, '')
});
}, [])
// arr.reduce((acc, ele) => acc.concat({
// value: ele,
// length: ele.length,
// withoutVowels: ele.replace(/(a|e|i|o|u)/gi, '')
// }), []);
}
// Given the following:
const users = [
{
id: 1,
name: 'ryan',
email: 'ryan@codeup.com',
languages: ['clojure', 'javascript'],
},
{
id: 2,
name: 'luis',
email: 'luis@codeup.com',
languages: ['java', 'scala', 'php'],
},
{
id: 3,
name: 'zach',
email: 'zach@codeup.com',
languages: ['javascript', 'bash'],
},
{
id: 4,
name: 'fernando',
email: 'fernando@codeup.com',
languages: ['java', 'php', 'sql'],
},
{
id: 5,
name: 'justin',
email: 'justin@codeup.com',
languages: ['html', 'css', 'javascript', 'php'],
},
];
// Use .reduce to transform the array into an object where the object's keys are ids and the values are objects that represent each user
const newObj = users.reduce((acc, {id, name, email, languages}) => {
acc[id] = {name, email, languages};
return acc;
}, {})
// Use .reduce to get a unique list of the languages the codeup instructors know
// From https://glitch.com/edit/#!/map-filter-reduce-practice
/**
* HINT: solve the map/filter/reduce problem with a foreach first
*/
// Reduce Problem #1
// given an array of names, use .reduce to produce a single string that contains everyone's name
var names = ["Ben", "Jafar", "Matt", "Priya", "Brian"];
const nameStr = names.reduce((acc, cur) => acc + cur);
const nameStr1 = names.reduce((acc, cur) => acc + cur, '');
const nameStr2 = names.reduce((acc, cur) => `${acc}${cur}`, '');
const nameStr3 = names.reduce((acc, cur) => `${acc}${cur}`);
var nameStr4 = '';
names.forEach(name => nameStr4 += name)
// Reduce Problem #2: Sum up all of the numbers in the following array using .reduce
let numbers = [1, 2, 3, 99, 1, -3, 1000, 0, 33, -67];
const sum = numbers.reduce((acc, cur) => acc + cur);
// Reduce Problem #3:
// Given the above array of numbers, write the .reduce necessary to determine the highest number of the array.
const highestNum = numbers.reduce((acc, cur) => acc >= cur ? acc : cur);
const highestNum1 = Math.max.apply('e', numbers);
// Reduce problem #4:
// Given the above array of numbers, write the .reduce necessary to determine the lowest number of the array.
const lowestNum = numbers.reduce((acc, cur) => acc <= cur ? acc : cur);
// Reduce problem #5:
// Given the array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], use .reduce to determine the average of all the numbers
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const averageNum = arr.reduce((acc, cur) => acc + cur) / arr.length;
// Reduce problem #6, given the array of numbers from above, determine the average of all numbers
const averageNum2 = numbers.reduce((acc, cur) => acc + cur) / numbers.length;
// Mapping problem #3
// Using .map to make a Projection
// Applying a function to a value and creating a new value is called a projection.
// each video object should make a new object containing only the id and the title.
// Your output should be a variable called idAndTitleColleciton and look like
/* [
* {"id": 70111470, "title": "Die Hard"},
* {"id": 654356453, "title": "Bad Boys},
* {"id": 65432445, "title": "The Chamber},
* etc...
* ];
*/
const idAndTitleColleciton1 = newReleases.map(ele => ({"id": ele.id, "title": ele.title}));
const idAndTitleColleciton = newReleases.map(({id, title}) => ({id, title}));
var newReleases = [
{
"id": 70111470,
"title": "Die Hard",
"boxart": "http://cdn-0.nflximg.com/images/2891/DieHard.jpg",
"uri": "http://api.netflix.com/catalog/titles/movies/70111470",
"rating": [4.0],
"bookmark": []
},
{
"id": 654356453,
"title": "Bad Boys",
"boxart": "http://cdn-0.nflximg.com/images/2891/BadBoys.jpg",
"uri": "http://api.netflix.com/catalog/titles/movies/70111470",
"rating": [5.0],
"bookmark": [{id: 432534, time: 65876586}]
},
{
"id": 65432445,
"title": "The Chamber",
"boxart": "http://cdn-0.nflximg.com/images/2891/TheChamber.jpg",
"uri": "http://api.netflix.com/catalog/titles/movies/70111470",
"rating": [4.0],
"bookmark": []
},
{
"id": 675465,
"title": "Fracture",
"boxart": "http://cdn-0.nflximg.com/images/2891/Fracture.jpg",
"uri": "http://api.netflix.com/catalog/titles/movies/70111470",
"rating": [5.0],
"bookmark": [{id: 432534, time: 65876586}]
}
];
// Challenge:
// Define a function named allIndexesOf that takes in two arguments. The first argument should be the array to search and the second argument should be the value you want to search for. If the item does not exist in the provided array, return an empty array;
// Recommend using .filter or .reduce inside of your allIndexesOf function to find the index.
// HINT: If you know your output will be an array, use an empty array as your initial value
// Given:
// allIndexesOf(fruits, "apple") should return the array [0, 3]
// allIndexesOf(fruits, "guava") should return the array []
// allIndexesOf(fruits, "pineapple") should return [4]
var fruits = ["apple", "banana", "orange", "apple", "pineapple"];
function allIndexesOf(arr, value) {
return arr.reduce((acc, ele, i) => ele === value ? acc.concat(i) : acc, []);
}
function allIndexesOf1(arr, value) {
return arr.map((e, i) => e === value ? i : -1).filter(ele => ele !== -1);
}
// Challenge:
// Define a function named removeAll(array, value) that takes in two arguments. The first argument should be an array and the second argument should be a value you wish to
// Given:
var bugs = ["mosquito", "ant", "scorpion", "ant", "ant", "mosquito", "typo", "reference error", "type error"];
function removeAll(arr, value) {
return arr.filter(ele => ele !== value);
}
// removeAll(bugs, "ant") should return ["mosquito", "scorpion", "mosquito", "typo", "reference error", "type error"]
// removeAll(bugs, "mosquito") should return ["ant", "scorpion", "ant", "ant", "typo", "reference error", "type error"]
// removeAll(bugs, "roach") should return the original array b/c "roach" has no occurrences.
const fruits = ["cantaloupe", "orange", "date", "elderberry", "ugli fruit", "pineapple"];
const customers = [
{
name: "Fred",
age: 58,
occupation: "Police Officer",
noOfPurchases: 4
},
{
name: "Samantha",
age: 54,
occupation: "Teacher",
noOfPurchases: 18
},
{
name: "Charles",
age: 38,
occupation: "Librarian",
noOfPurchases: 9
}
];
// PROBLEM 1 - create an array of the first letters of each fruit
//HINT: use .map()
const firstLetterFruits = fruits.map(ele => ele.charAt(0));
// PROBLEM 2 - create array of user objects based on the customers array of
//objects (each user object should just have name and age properties)
//HINT: use .map()
// PROBLEM 3 - create an array of civil servant customers (teachers and police
//officers) containing the same properties as the objects on the
//customers objects
//HINT: use .filter()
// PROBLEM 4 - determine the average age of customers
//HINT: use .reduce()
/* ---------------------------------------------------------------------- */
// Given the following array...
const names = ["John", "Max", "Ronald"];
// complete the bonuses below...
// - Create an array where all names are given a last name of Smith.
const newArr = names.map(ele => `${ele} Smith`);
// - Create an array where each word is in all caps
const newArr1 = names.map(ele => ele.toUpperCase());
// - Create an array where all names have more than 3 letters
const newArr2 = names.filter(ele => ele.length > 3);
// - Create an array of names with only the last two letters of each name
const newArr3 = names.map(ele => ele.slice(-2));
// - Create a total count of all letters
const newArr4 = names.reduce((acc, cur) => acc + cur.length, 0);
// - Create a string of all letters in alphabetical order
const newStr = names.reduce((acc, cur) => acc + cur).toLowerCase().split('').sort().join('');
// - Create an array of word objects with properties of wordLength, firstLetter, lastLetter
const newArr5 = names.map(ele => ({
wordLength: ele.length,
firstLetter: ele.charAt(0),
lastLetter: ele.slice(-1)
}));
// - Create a string of all vowels in the entire array of names
const newStr1 = names.reduce((acc, cur) => acc + cur).replace(/[^aeiou]/gi, '');
// - Create a single object with properties ???
/* ---------------------------------------------------------------------- */
// Given the following array...
const family = [
{
name: "Karen",
gender: "female",
age: 29,
},
{
name: "Summer",
gender: "female",
age: 10,
},
{
name: "Bob",
gender: "male",
age: 32,
},
];
// complete the bonuses below...
// - Calculate the average age of family members
const averageAge = family.reduce((acc, {age}) => acc + age, 0) / family.length;
// - Create an array of family objects without the age property
const familyObj = family.map(({name, gender}) => ({name, gender}));
const familyObj1 = family.map(e => ({name: e.name, gender: e.gender}));
// - Create an array of all minors
const minors = family.filter(ele => ele.age <= 18);
// - Calculate the total age combined of family members
const totalAge = family.reduce((acc, cur) => acc + cur.age, 0);
// - Create an array of only female family member objects
const femaleFamily = family.filter(ele => ele.gender === "female");
const femaleFamily1 = family.filter(({gender}) => gender === "female");
// - Create a single object with properties containing arrays of all names, genders, and ages
const familyObject = family.reduce((acc, cur) => {
acc.names.push(cur.name);
acc.genders.push(cur.gender);
acc.ages.push(cur.age);
return acc;
}, {names: [], genders: [], ages: []});
}
</script>
</body>
</html>