본문 바로가기
JavaScript/Youtube

JavaScript/Traversy Media - Higher Order Functions & Arrays

by SKim입니다 2020. 6. 22.

Higher Order Arrays Methods를 배우고

(forEach, filter, map, sort, reduce)

ES6 arrow function을 이용해서

더 짧고 elegant하게 write하는 방법을 알아보겠다.

 

 

두 개의 array가 있다.

1) companies - name, category, start, end date를 가진 object들이 들어있다.

2) age - 숫자들

 

 

 

1. forEach - for loop와 비교

 (1) for loop

 

 (2) forEach

  companies.forEach 뒤에 callback 함수를 취한다.

  (asynchronous가 아니라 synchronous callback이다.)

 

  이것은 세 가지를 take in(pass in)할 수 있다.

   ① iterator - we can use for each company or whatever is in the array

   ② index

   ③ entire array (companies)

 

company를 넣고 돌렸더니 똑같은 결과가 나온다.

 

만약 name만 보고싶다면 .name을 입력한다.

 

 

 

2. filter

 (1) for loop

 

 (2) filter

ES6 arrow function을 이용하면

더 줄여서 한 줄로 만들 수도 있다.

 

* filter retail companies

 

* Get 80s companies

* Get companies that lasted 10 years or more

 

 

3. map

* Create array of company names

 

 

루트, *2

 

두 개를 합칠 수도 있다.

 

이럴 때는 보통 이렇게 쓴다.

 

4. sort

* sort companies by start year

 

* sort ages

첫번째 숫자 기준으로 sort된다.

 

 

 


5. reduce

ages를 다 더하기

0: total은 0에서 시작

Get total years for all companies

 

 

 

 

 

6. Combine methods

 

 

 

 

 

 

youtu.be/rRgD1yVwIvE

 

댓글