[Javascript] High Order Method & Array

phoenix·2021년 9월 25일
0

너무나도 자주 쓰이고 자주 들어봤떤 High Order Method & Array에 대해 알아보자!
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}
];

먼저 우리는 companies라는 배열을 가지고 시작한다

High Order Method를 쓰기 전에 먼저 기본적인 for Loop을 해보겠다

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

이렇게 for loop을 돌리면 companies 배열에 있는 각각의 companies가 출력 된다

이제 for loop 대신에 high order method중 하나인 forEach를 사용 해 보겠다!

forEach

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

forEach를 써도 똑같은 결과가 출력되고 훨신더 깔끔하게 출력이 된다.

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

그냥 컴퍼니의 이름만 출력하고 싶을떄는 company.name을 통해서 해주면 된다!

Filter

const ages = [33, 12, 20, 16, 5, 54, 21, 44, 61, 13, 15, 45, 25, 64, 32];

먼저 filter에 대해 배우기전에 ages라는 나이가 담긴 배열을 만들었다.

그리고 위와같이 High Order Method 대신 for loop으로 먼저 진행을 해봤다

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

console.log(canDrink)

이렇게 하면은 canDrink라는 빈배열안에 if 조건문에 부합하는 21살이거나 더 많은 나이가 push를통해 들어가게 된다

이 방법을 filter로 변환하면

const canDrink = ages.filter(function(age) {
  if(age >= 21) {
    return true;
  }
})

console.log(canDrink)

이렇게 쓰고 똑같은 결과값이 출력되는거를 알 수 있다

ES6의 arrow function을 사용하면은 더욱더 간결한 코드를 작성 할 수 있다 const Arrow = () => {}

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

console.log(canDrink)

ages.filter() 소괄호안에 function을 넣는대신 arrow function으로 대체해 훨씬 더 깔끔한 코드를 작성할 수 있다

위에있는 Companies 배열을통해 filter를 한번 더 복습 해보자
company의 category가 retail인 company를 filter를 해보자

//filter retail companies
const retailCompanies = companies.filter( company => {
  if (company.category === 'Retail') {
    return true;
  }
})

console.log(retailCompanies)

Map

맵을 통해 새로운 ARRAY를 만들어 낼 수 있다

//create array of company names
const companyNames = companies.map(company => {return company.name})

console.log(companyNames)

Map을 통해 ages 배열에 있는 각각의 나이를 *2를 해볼수도 있다

//ages * 2
const agesTimesTwo = ages.map(age => age * 2);
console.log(agesTimesTwo);

Map을 한번만 하는게 아니라 map을 한 상태에서 또 다시 map을 할 수 있다

//mapping twice
const ageMap = ages
.map(age => Math.sqrt(age))
.map(age => age *2);

console.log(ageMap)

이렇게 하면은 먼저 ages에있는 age값들을 Math.sqrt을통해 제곱을 하고 그다음에 또다시 그 제곱된 ages 배열에있는 age값들을 다시 *2를 해준다 그리고 출력은 최종 결과 값이다

Sort

companies배열에 있는 company들의 시작연도에 따라 배열을 sort할 수 있다

//sorting companies based on thier start year
const sortedCompanies = companies.sort( (a,b) => (a.start > b.start ? 1 : -1));

console.log(sortedCompanies);

여기서 삼항연산자를 사용하여 a의 시작연도가 b의 시작연도보다 클때 1 true를 리턴하고 아니면 -1 false를 리턴한다

[
  {
    name: 'Company Nine',
    category: 'Retail',
    start: 1981,
    end: 1989
  },
  {
    name: 'Company One',
    category: 'Finance',
    start: 1981,
    end: 2003
  },
  {
    name: 'Company Seven',
    category: 'Auto',
    start: 1986,
    end: 1996
  },
  {
    name: 'Company Six',
    category: 'Finance',
    start: 1987,
    end: 2010
  },
  {
    name: 'Company Four',
    category: 'Retail',
    start: 1989,
    end: 2010
  },
  {
    name: 'Company Two',
    category: 'Retail',
    start: 1992,
    end: 2008
  },
  {
    name: 'Company Three',
    category: 'Auto',
    start: 1999,
    end: 2007
  },
  {
    name: 'Company Five',
    category: 'Technology',
    start: 2009,
    end: 2014
  },
  {
    name: 'Company Eight',
    category: 'Technology',
    start: 2011,
    end: 2016
  }
]

이번에는 ages배열에있는 age값들을 sort를 해보자

//sort ages
const sortAges = ages.sort();
console.log(sortAges);

이렇게 할때에는 값이 이상하게 출력이된다 왜냐하면 그냥 sort()를하면 맨 앞자리의 숫자만 보고 sort를 한다

예를 들어 14와 2둘중에 더 작은건 2인데 14가 더 앞에 나오는 식으로 sort가 된다

따라서 이거를 수정하기 위해서는

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

해주면 된다 역순으로 sort를 하고 싶을 때에는

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

b - a를 통해 역순으로 sort가 된다

Reduce

Reduce를 통해 sum값을 얻을수가 있다
ages배열에 있는 age값을 reduce를 통해 다 더해진 값을 출력 할 수 있다

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

이러게하면 모든 age값이 다 더해진 값이 출력된다 460

지금까지 배운 High Order Methods를 다 합쳐서 사용을 할 수 있다

//combine methods
const combined = ages
.map(age => age *2)
.filter(age => age >= 40) 
.sort((a,b) => a - b)
.reduce( (a,b) => a + b, 0)

console.log(combined)

먼저 ages배열에 있는 모든 age값들을 *2를 해주고

그다음 age 값중에서 40보다 크거나 같은 값들을 filter 해준다

그뒤 a - b sort를 통해 값을 순서대로 나열하고

reduce를 통해 순서대로 나열된 age값들을 다 더한 총 합을 구한다.

profile
phoenix

0개의 댓글