[Array] reduce()

Sejung Seo·2022년 6월 16일
0

JavaScript

목록 보기
8/19
post-thumbnail
post-custom-banner
const array = [3, -1, 10, 5, 0]

const sum = array.reduce(function(accumulator, currentValue){
  //console.log(accumulator)	//3	//2	//12 //17
  //console.log(currentValue)	//-1 //10 //5 //0
  return accummulator + currentValue
})
console.log(sum) //17

const sum1 = array.reduce((acc, value) => acc + value)
console.log(sum1) //17

let array2 = [
  {name: "james",
  age: 20},
  {name: "tom",
  age: 25},
  {name: "terry",
  age: 30},
  {name: "peter",
  age: 35},
]
let sum3 = array2.reduce((acc, value) => acc + value.age, 0)
console.log(sum3) // 110 // 0 초기값 안넣어줄때 결과값: 20253035
console.log(sum3/array2.length)	//평균값 : 27.5

참고링크 https://youtu.be/nIc6a8v0Dys

profile
공부하는 코린이 🌼
post-custom-banner

0개의 댓글