Open2
TS/JS marathon codes
![Nori](https://res.cloudinary.com/zenn/image/fetch/s--mnrSVs7B--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_70/https://storage.googleapis.com/zenn-user-upload/avatar/3295a7ddbc.jpeg)
2024.02.11(日) TS ▶ reduce()
let arr: number[] = [1,2,3,4,5,6,7,8,9,10];
let outcome: number = arr.reduce(
(acc,cur)=>
{
return acc+cur;
}
)
console.log(outcome
// outcome = 55
let arr: number[] = [1,2,3,4,5,6,7,8,9,10];
let outcome: number = arr.reduce(
(acc,cur)=>
{
return acc+cur;
},
//set an initial value "10"
10
)
console.log(outcome)
// outcome = 65
initial value + (acc + cur) = outcome
10 + {(0+1)}
10 + {(1+2)}
.
.
.
10 + {(45+10)} = 65
👇平均値を求める
let arr: number[] = [1,2,3,4,5,6,7,8,9,10];
let outcome: number = arr.reduce(
(acc,cur)=>
{
return acc+cur
}
)
let average: number = outcome/arr.length
console.log(average)
// average = 5.5
👇Object Literalの中の合計値を出す
interface Kureshin {
name: string;
age: number;
}
const noharake: Kureshin[] =[
{name: "Shin-nosuke", age: 5},
{name: "Misae", age:29},
{name: "Hiroshi", age:35},
{name: "Himawari", age: 0},
{name: "Shiro", age:3}
]
let totalAge: number =
noharake.reduce(
(acc,cur)=>
{
return acc+cur.age
},
0
)
console.log(totalAge)
// totalAge = 5+29+35+0+3 = 72