내장 메소드 정리 : map(), filter(), reduce()

frenchkebab·2021년 8월 19일
0

javascript 문법

목록 보기
3/4
post-thumbnail

1. map() 메소드

1-1. 구문

arr.map(callbackFunction(currentValue, index, array), thisArg);
  • currentValue : 배열 내 현재값
  • index
  • array : 현재 배열
  • thisArg : 콜백함수 내에서 this로 사용될 값

1-2. 예시

>  a = [10, 11, 12, 13, 14, 15];
   let answer = a.map( (v, i) => {
       return v*v;
   });
   console.log(answer);
   
[100, 121, 144, 169, 196, 225]

1-3. 주의사항

1-3-1. return된 배열의 길이는 원본 배열의 길이와 동일해야 한다

> a = [10, 11, 12, 13, 14, 15];
  let answer = a.map( (v, i) => {
    if(v%2 === 0) return v;
  });
  console.log(answer);

[10, undefined, 12, undefined, 14, undefined]

2. filter() 메소드

2-1. 예시

let data = [
    { name: 'jack', age: 20 },
    { name: 'kevin', age: 16 },
    { name: 'rick', age: 27 },
    { name: 'marry', age: 21 },
    { name: 'rilly', age: 19 }
  ];

let result = data.filter((x) => {
  return x.age >= 20;
});

console.log(result);

<실행 결과>

😮 map() 함수와는 다르게 검색 조건으로 새로운 배열을 생성해준다!

3. reduce() 메소드

3-1. 구문

const numberList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 
 
const totalResult = numberList
	.reduce((initialValue, currentValue, currentIndex, array) => {
    return initialValue + currentValue;
}, 0);

3-2. reduceRight 메소드

reduce() 메소드와 동일하되, 오른쪽 원소부터 순회한다.

3-3. 읽어볼 것

https://www.zerocho.com/category/JavaScript/post/5acafb05f24445001b8d796d

해당 링크 글을 읽고 reduce() 메소드에 대해 좀 더 깊게 이해하자

profile
Blockchain Dev Journey

0개의 댓글

관련 채용 정보