-
Notifications
You must be signed in to change notification settings - Fork 0
/
24_transformArrayReduceChallenge.js
46 lines (35 loc) · 1.36 KB
/
24_transformArrayReduceChallenge.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
const cars = [
{ name: "Toyota", isElectric: false, weight: 1320 },
{ name: "Ford", isElectric: false, weight: 1400 },
{ name: "Volkswagen", isElectric: false, weight: 1370 },
{ name: "Honda", isElectric: false, weight: 1375 },
{ name: "Tesla", isElectric: true, weight: 1750 },
{ name: "BMW", isElectric: true, weight: 1350 },
];
// challenge 1 totalkan semua weight mobil
const totalWeight = cars.reduce((acc,car)=>{
return acc + car.weight
},0) // nol (0) adalah initial value
console.log(`berat total semua mobil = ${totalWeight}`);
// challenge total mobil listrik saja (versi sendiri)
// const carListrik = cars.filter(car=> car.isElectric)
// console.log(carListrik);
// const listrikWeigh = carListrik.reduce((acc,mboil)=>{
// return acc + mboil.weight
// },0)
// console.log(listrikWeigh)
// versi chaining (bikinan sendiri)
const listrikWeight = cars.filter(car=> car.isElectric).
reduce((acc,mboil)=>{
return acc + mboil.weight
},0)
console.log(`berat total mobil listrik ${listrikWeight}`);
// versi sepuh scrimba ( bjir cuma pake conditional)
const totalWeightListrik = cars.reduce((akumulator,mboil)=>{
if (mboil.isElectric){
return akumulator + mboil.weight;
} else {
return akumulator;
}
},0)
console.log(`total berat mobil listrik versi code sepuh scrimba ${totalWeightListrik}`);