.

[js] 배열의 reduce (멋지다), map 본문

카테고리 없음

[js] 배열의 reduce (멋지다), map

cuveloper 2019. 11. 12. 11:46

 

## reduce

The reduce() method reduces the array to a single value.

The reduce() method executes a provided function for each value of the array (from left-to-right).

The return value of the function is stored in an accumulator (result/total).

Note: reduce() does not execute the function for array elements without values.

Note: this method does not change the original array.

 

- 원본배열 수정안하고, 값 없으면 안돌아가고, 반환값은 알아서 축적기에 저장하고, 배열의 각 값에 접근하기에 좋다! (for를 안돌려도 값 비교를 할 수 있다!!!!)

 

total: initalValue 가 들어감(initalValue: a value to be passed to the function: 함수 뒤에 initalValue 따로 설정 안하면 배열의 첫번째 요소가 들어감,  return된 값이 들어감, accumulator)

current: currentValue (쉽게 배열의 두번째 인덱스 값이 current라고 보면 됨 [total이 초기화 안했을 경우])

 

배열 최대값, 최소값 비교의 여러 버전1 : Math객체보다 메모리 소모가 적은 방법 (이거 보다 매력적이어서 get)

var array = [1, 10, 5, 11, 2];

//최대값
var max = array.reduce( function (previous, current) { 
	return previous > current ? previous:current;
});

//최소값
var min = array.reduce( function (previous, current) { 
	return previous > current ? current:previous;
});

배열 최대값, 최소값 비교의 여러 버전2 : Math 객체 이용 (큰 배열 일경우 rangeError 가능성)

Math.max.apply(null, 배열); // 최대값
Math.min.apply(null, 배열); //최소값

var test = [0, 77, 33, 11, 99, 88, 55];

Math.max.apply(null, test); //결과값은 99
Math.min.apply(null, test); //결과값은 0

배열 최대값, 최소값 비교의 여러 버전3 : Array 내장 메소드 사용

var min = [1, 20, 11, 88, 3].slice(0).sort(function(a,b){a>b})[0];
var max = [1, 20, 11, 88, 3].slice(0).sort(function(a,b){a<b})[0];

["b","a","d","c"].slice(0).sort()[0]; //"a"
["b","a","d","c"].slice(0).sort().reverse()[0]; //"d"
["b","a","d","c"].slice(0).sort(function(a,b){return a > b;})[0]; //"a"
["b","a","d","c"].slice(0).sort(function(a,b){return a < b;})[0]; //"d"

 

.reduce initalvalue 설정한 예제 (cf: reduce와 map) : 2배수 구하기

var data = [1, 2, 3];

var initialValue = [];
var reducer = function(accumulator, value) {
  // initialValue = []; 에 값을 받을 새로운 배열을 선언했음
  accumulator.push(value * 2);
  // value는 첫번째 값 (만일 초기화를 안해줬음 두번째 값?)
  return accumulator;
};
var result = data.reduce(reducer, initialValue);
console.log(result); // [2, 4, 6]

// reduce보다 map이 더 짧고 직관적
var result2 = data.map(x => x * 2);
console.log(result2); // [2, 4, 6]

.reduce initalvalue 설정한 예제 (cf: reduce와 filter) : 홀수 구하기

var data = [1, 2, 3, 4, 5, 6];

var initialValue = [];
var reducer = function(accumulator, value) {
  if (value % 2 != 0) {
    // 홀수의 값을 새로운 배열에 넣는다
    accumulator.push(value);
  }
  return accumulator;
};
var result1 = data.reduce(reducer, initialValue);
console.log(result1); // [1, 3, 5]

var result2 = data.filter(x => x % 2 != 0);
/*
var result2 = data.filter(function(x){return x % 2 != 0});
// retrun 결과에 통과한 아이들은 새로운 배열에 반환된다(그 배열이 x)
// return 이 true를 반환하면 요소를 유지하고, false를 반환하면 버린다
// x % 2 != 0 x에 홀수의 값이 올 경우 true이므로 값을 유지하고, 짝수가 오면 false이기 때문에 버린다.
// x에는 홀수의 값이 차게 된다.
*/
console.log(result2); // [1, 3, 5]

 

.reduce initalvalue 설정한 예제 (cf: reduce와 map + filter) : 홀수의 배수 구하기

var data = [1, 2, 3, 4, 5, 6];

var initialValue = [];
var reducer = function(accumulator, value) {
  if (value % 2 != 0) {
    accumulator.push(value * 2);
    //배열을 1번 순회함
  }
  return accumulator;
}
var result1 = data.reduce(reducer, initialValue);
console.log(result1); // [2, 6, 10]

var result2 = data.filter(x => x % 2 != 0).map(x => x * 2);
// 배열을 2번 순회함(filter에서 원본 배열로한번, map에서 filter에서 나온 배열로 한번)
console.log(result2); // [2, 6, 10]

//filter+map 이 개인적으로 훨씬 더 직관적인 것으로 보이지만, 
//reducer 라는 함수로 로직이 따로 빠져있는, reduce 가 더 재사용성이 있어 보임.

 

#### map = 원본 배열을 활용하여 새로운 배열을 만드는 방법

The map() method creates a new array with the results of calling a function for every array element.

The map() method calls the provided function once for each element in an array, in order.

Note: map() does not execute the function for array elements without values.

Note: this method does not change the original array.

 

 

 

 

 

https://medium.com/@hongkevin/js-3-%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%EB%B0%B0%EC%97%B4-%EB%A9%94%EC%84%9C%EB%93%9C-reduce-100-%ED%99%9C%EC%9A%A9%EB%B2%95-feat-egghead-io-97c679857ece

Comments