4가지 모두 공통적으로 고차함수이다.
*고차 함수: 자신의 매개변수에 함수를 전달 받는 것

 

1. forEach

function forEach(predicate, thisArg) {
	for(let i=0; i<a.length; i++) {
    	predicate(a[i], i); // 반복해서 호출하는 것
    }
}

a = [10, 11, 12, 13, 14, 15];
a.forEach(function(v, i){ // 인자로 callback함수를 넘겨준다.
	console.log(v, i)
});

 

2. map

원본 배열을 하나하나 탐색하면서 새로운 배열을 생성한다.

function map(predicate, thisArg) {
	// 새로운 배열 생성
	let list=[];
    for(let i=0; i<a.length; i++) {
    	list.push(predicate(a[i], i));
    }
    return list;
}

a = [10, 11, 12, 13, 14, 15]
let answer = a.map(function(v, i) {
	return v*v;
});

console.log(answer); // [100, 121, 144, 169, 196, 225]

새로운 배열을 넘겨받을 수 있고, 중요한 것은 새로운 배열과 원본 배열의 길이는 같다. 

let answer = a.map(function(v, i){
	if (v%2 == 0) return v; // [10, undefined, 12, undefined, 14, undefined]
};

만약 위와 같이 11, 13, 15와 같이 홀수인 값은 return되지 못해 undefined 값을 푸시한다.

 

3. filter

map과 같이 새로운 배열을 생성하지만, 말그대로 filter 즉, 걸러준다고 생각하자!

filter는 원하는 원소만 배열을 생성해서 return 해준다.

let answer = a.map(function(v, i){
	if (v%2 == 0) return v; // [10, 12, 14]
};

따라서 map과는 다르게 원본과 생성된 배열의 길이가 같지 않다

 

 4. reduce

배열의 각 요소를 순회하며 callback 함수의 실행 값을 누적하여 하나의 결과 값을 반환한다.

function reduce(predicate, arg) {
	let result = arg; // 넘어온 값을 초기화한다.
    for(let i=0; i<a.length; i++) {
    	result = predicate(result, a[i]);
    }
    return result;
}
a = [10, 11, 12, 13, 14, 15]
answer = a.reduce(function(accumulate, v){
	return accumulate + v;
}, 0);

 

처음에 result에 0이 들어가고,

0 + 10 = 10

10 + 11 = 21

21 + 12 = 33 
...

결국 10 ~ 15를 더하게 된다!

 

 

 

*출처: 해당 코드들은 인프런 [자바스크립트 알고리즘 문제풀이 입문]을 들으며 수강한 내용입니다.

+ Recent posts