-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy path4-array.js
More file actions
66 lines (53 loc) · 1.02 KB
/
4-array.js
File metadata and controls
66 lines (53 loc) · 1.02 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
var data = [
{
name: "Butters",
age: 3,
type: "dog"
},
{
name: "Lizzy",
age: 6,
type: "dog"
},
{
name: "Red",
age: 1,
type: "cat"
},
{
name: "Joey",
age: 3,
type: "dog"
},
{
name: "Pochi",
age: 3,
type: "dog"
}
];
// write a function that will sum all of the dogs ages in dog years using for loop.
// 1 human year = 7 dog year
// your code goes here
var sum = 0;
function sumDogAge() {
for (var i = 0; i < data.length; i++) {
if (data[i].type == 'dog') {
sum += data[i].age * 7;
}
}
}
sumDogAge(); // 105
// Solution is 105
// Write the same function using
// 1. filter - for filtering the cat or dog
// 2. map - to multiply human year to dog year
// 3. reduce - to accumulate total age.
// Solution 105
function sumDogAge() {
var typeDog = data.filter(element => element.type == 'dog');
var dogYear = typeDog.map(element => element.age * 7);
var sum = dogYear.reduce((x, y) => x + y);
return sum;
}
sumDogAge();
// Solution 105