본문 바로가기

JavaScript

JavaScript - 함수( 화살표 , map(), reduce(),filter())

1. 화살표 함수 (arrow function)

: function 키워드 대신 화살표(=>)를 사용하여 간략한 방법으로 함수를 선언

 

// 익명 함수  표현식을 이용한 함수 정의
let add = function(a, b) { return a+b };

//화살표 함수
let add2 = (a, b) => { return a+b };

// 한줄일 경우 중괄호를 생략하면 화살표 오른쪽의 결과를 반환
let add3 = (a, b) => a+b;

// 파라미터가 하나일 경우 파라미터를 감싸고 있는 소괄호도 생략 가능
let add4 = a => a+4;

// 객체를 반환하는 경우에는 소괄호로 감싸야 함
let add5 = (a, b) => {return {result:a+b}};
let add6 = (a, b) => ({result:a+b});

 

2. map 함수

: 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환

const numbers = [1, 4, 9, 16] ;

const twoTimes = numbers.map(number => number * 2);
console.log(twoTimes); 		// [2, 8, 18, 32]

const f = value => value *2;
const twoTimes = numbers.map(f)

const g = value => value *10 ;

const gop = numbers.map(f).map(g);
console.log(gop)		// [20, 80, 180, 320]

3. filter 함수

: 입력한 조건을 바탕으로 데이터를 필터링하는 함수

const words = [ 'srpay', 'limit', 'elite', 'destruction', 'present', 'exuberant' ];

// 길이가 여섯 글자 이상인 단어만 추출

const newWords = words.filter(word => word.length >= 6);
console.log(newWords);		// ['destruction', 'present', 'exuberant']

 

+) map함수 + filter 함수

// 짝수만 추출해서 10배수한 결과를 출력

const numbers = [ 1, 3, 4, 6, 11, 14 ];

const newNum = numbers.filter(number => number % 2 === 0).map(number => number *10);
console.log(newNum);		// [40, 60, 140]

4. reduce 함수

:  배열의 요소를 하나로 줄이는 작업을 수행

const numbers = [ 1, 2, 3, 4, 5 ];

let sum = numbers.reduce((previous, current) => previous + current);
console.log(sum);

// 각 과목의 총합 구하기
let scores = [];
scores[0] = {name: '홍길동', korean: 80, math: 90, english: 90};
scores.push({name: '고길동', korean: 90, math: 80, english: 80});
scores.push({name: '신길동', korean: 70, math: 80, english: 70});
console.log(scores);

const fk = scores.map(s => s.korean).reduce((p, c) => p+c);
const fe = scores.map(s => s.english).reduce((p, c) => p+c);
const fm = scores.map(s => s.math).reduce((p, c) => p+c);

console.log('국어 점수 총합', fk);		// 국어 점수 총합 240
console.log('영어 점수 총합', fe);		// 영어 점수 총합 240
console.log('수학 점수 총합', fm);		// 수학 점수 총합 250

 

728x90