환경
이 문서는 유튜버 Traversy Media님의 영상을 보고 filter, map, 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]
위의 더미데이터를 활용해서 각 메서드의 특징을 알아보겠습니다.
기존에는 for문을 사용해 데이터를 가공했습니다.
for (let i = 0; i < companies.length; i++) {
console.log(companies[i])
}
이제는 for문 대신에 아래 메서드를 이용해 더 세련된 문법을 구사할 수 있습니다.
companies.forEach(function (company, index, companies) {
console.log(company, index)
})
// 결과
{ 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 }
콜백은 3가지 인수를 받습니다.
const canDrink = ages.filter(age => age >= 21)
console.log(canDrink)
// 결과
[ 33, 54, 21, 44, 61, 45, 25, 64, 32 ]
const retailCompanies = companies.filter(function (company) {
if (company.category === 'Retail') { return true }
})
console.log(retailCompanies)
// 결과
[ { name: 'Company Two',
category: 'Retail',
start: 1992,
end: 2008 },
{ name: 'Company Four',
category: 'Retail',
start: 1989,
end: 2010 },
{ name: 'Company Nine',
category: 'Retail',
start: 1981,
end: 1989 } ]
retailCompanies
는 아래처럼 함축하여 사용할 수 있습니다.:
const retailCompanies = companies.filter(company => company.category === 'Retail')
각 요소를 테스트해서 true를 반환하면 요소를 유지하고, false를 반환하면 버립니다.
callback 테스트를 통과하지 못한 배열 요소는 그냥 건너뛰며 새로운 배열에 포함되지 않습니다.
콜백은 3가지 인수를 받습니다.
♻️ 반환
테스트를 통과한 요소로 이루어진 새로운 배열.
어떤 요소도 테스트를 통과하지 못했다면 빈 배열을 반환.