본문 바로가기
공부_정리☆★

정리_JavaScript/Traversy - Higher Order Functions & Arrays

by SKim입니다 2020. 6. 23.

forEach, filter, map, sort, reduce

const companies = [
    {name: "Company One", category: "Finance", start: 1981, end: 2003},
    {name: "Company Two", category: "Retail", start: 1992, end: 2008},
    {name: "Company Three", category: "Auto", start: 1999, end: 2007},
    {name: "Company Four", category: "Retail", start: 1989, end: 2010},
    {name: "Company Five", category: "Technology", start: 2009, end: 2014},
    {name: "Company Six", category: "Finance", start: 1987, end: 2010},
    {name: "Company Seven", category: "Auto", start: 1986, end: 1996},
    {name: "Company Eight", category: "Technology", start: 2011, end: 2016},
    {name: "Company Nine", category: "Retail", start: 1981, end: 1989}
  ];
  
  const ages = [33, 12, 20, 16, 5, 54, 21, 44, 61, 13, 15, 45, 25, 64, 32];

 

 

 

1. 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)

 

* 모든 정보 보여주기

  for (let i = 0; i < companies.length; i++) {
    console.log(companies[i]);
  }

  companies.forEach(function(company) {
    console.log(company);
  });

  companies.forEach(function(x) {
    console.log(x);
  });

이 세 가지는 같다.

 

* company의 name만 보여주기

  for (let i = 0; i < companies.length; i++) {
    console.log(companies[i].name);
  }

  companies.forEach(function(company) {
    console.log(company.name);
  });

  companies.forEach(function(x) {
    console.log(x.name);
  });

이 세 가지도 같다.

 

 

 

2. filter

* 21살 이상만 filter하기

let canDrink = [];
for (let i = 0; i < ages.length; i++) {
  if (ages[i] >= 21) {
    canDrink.push(ages[i]);
  }
}

const canDrink = ages.filter(ages => ages >= 21);

const canDrink = ages.filter(x => x >= 21);

세 가지는 같다.

 

* 카테고리가 Retail인 company만 filter해서 전체 정보 보여주기

const retailCompanies = companies.filter(function(company) {
  if (company.category === "Retail") {
    return true;
  }
});

const retailCompanies = companies.filter(company => company.category === "Retail");

const retailCompanies = companies.filter(x => x.category === "Retail");

세 가지는 같다.

 

* start가 80년대인 company만 filter해서 전체 정보 보여주기

const eightiesCompanies = companies.filter(company => company.start >= 1980 && company.start < 1990);

 

* 10년 이상 지속된 company만 filter해서 전체 정보 보여주기

const lastedTenYears = companies.filter(company => (company.end - company.start >= 10));

 

 

 

3. map

* company의 이름들로 array 만들기

const companyNames = companies.map(company => company.name);

 

* Company One [1981 - 2003] 이런 식으로 array 만들기

const companyHistory = companies.map(company => `${company.name} [${company.start} - ${company.end}]`);

 

* 나이를 각각 루트하기 / 두 배 하기

const ageSquare = ages.map(age => Math.sqrt(age));

const ageTimesTwo = ages.map(age => age * 2);

 

* 나이를 각각 루트하고 두 배 하기

const ageSquareTimesTwo = ages
  .map(age => Math.sqrt(age))
  .map(age => age * 2);

const ageSquareTimesTwo = ages.map(age => Math.sqrt(age) * 2);

두 가지는 같다.

 

 

 

4. sort

* company를 start year 기준으로 sort하기

const sortedCompanies = companies.sort(function (c1, c2) {
  if (c1.start > c2.start) {
    return 1;
  } else {
    return -1;
  }
})

const sortedCompanies = companies.sort((a, b) => (a.start > b.start ? 1 : -1));

두 가지는 같다.

 

* age를 적은 순 / 많은 순으로 sort하기

const sortedAgesA = ages.sort((a, b) => a - b);

const sortedAgesD = ages.sort((a, b) => b - a);

만약 (a, b) => a - b를 안 쓰면

맨 왼쪽 자리 숫자 기준으로 sort된다.

 

 

 

5. reduce

* age를 다 더하기

let ageSum = 0;
for (let i = 0; i < ages.length; i++) {
  ageSum += ages[i];
}

const ageSum = ages.reduce(function(total, age) {
  return total + age;
}, 0)

const ageSum = ages.reduce((total, age) => total + age, 0);

const ageSum = ages.reduce((a, b) => a + b, 0);

네 가지는 같다.

맨 뒤의 0은 total을 0으로 시작한다는 뜻이다.

 

* company가 지속된 기간을 다 더하기

const totalYears = companies.reduce(function(total, company) {
  return total + (company.end - company.start);
}, 0);

const totalYears = companies.reduce((total, company) => total + (company.end - company.start), 0);

두 가지는 같다.

 

 

 

 

youtu.be/rRgD1yVwIvE

 

댓글