[Javascript] map와 filter 활용 예시

bongbong·2022년 5월 20일
1
post-thumbnail

map과 filter 메서드의 차이점을 제대로 알아보고 이들의 활용 예시들을 공부해보려 한다.

map

  • map은 콜백함수의 반환값들로 이루어진 새로운 배열을 반환한다.
const numbers = [1,4,9];

const roots = numbers.map(item => Math.sqrt(item));

console.log(roots); //[1,2,3];
console.log(numbers); //[1,4,9];
  • map은 map 메서드를 호출한 배열과 map 메서드가 생성하여 반환한 배열을 1:1 매핑한다.
  • map 메서드는 콜백함수를 호출하면서 (요소값, index, this)의 인수를 전달한다.
[1,2,3].map((item, index, arr)=> {
    console.log(item, index, arr);
    return item;
})
// 1 0 [1,2,3]
// 2 1 [1,2,3]
// 3 2 [1,2,3]

filter

  • 콜백함수의 반환값들이 true인 요소로만 구성된 새로운 배열을 반환
const numbers = [1,2,3,4,5];

const odds = numbers.filter(item => item %2);
console.log(odds); //[1,3,5]
  • 콜백함수를 호출하면서 (요소값, index, this)의 인수를 전달한다.
[1,2,3].filter((item, index, arr)=>{
    console.log(item,index,arr);
    return item %2;
});

map/filter의 활용 예시

배열 내 객체에서 원하는 프로퍼티 값만 가져오기

const testArray = [
  {title:'첫번째 글목록입니다.', content_id:1, user_id:'seyoung'},
  {title:'두번째 글목록입니다.', content_id:2, user_id:'hayoung'},
  {title:'세번째 글목록입니다.', content_id:3, user_id:'taeyoung'},
]

const resultArray = testArray.map((data) => {
	return data.user_id
})
//[ 'seyoung', 'hayoung', 'taeyoung' ]

배열 내 조건에 맞는 데이터만 가져오기

const numberList = [1,2,5,77,23,4];

const resultList = numberList.filter((num) => {
    return num < 10;
})
console.log(resultList) //[1,2,5,4]

배열 내 특정 단어를 포함하는 데이터만 가져오기

const list = ['김사원','윤대리','한주임','윤상무','김주임','최사장','황차장', '김과장'];

const resultList = list.filter(data => data.indexOf('주임') !== -1)
//[ '한주임', '김주임' ]

배열 내 원하는 조건의 요소와, 원하는 프로퍼티 키 가져오기

const testArray = [
  {title:'js 질문이요', content_id:'1', user_id:'sese'},
  {title:'typescript 질문이요', content_id:'2', user_id:'nana'},
  {title:'개발공부 어떻게 하나요', content_id:'3', user_id:'haha'},
  {title:'제 질문에 답좀 부탁드려요', content_id:'4', user_id:'sese'}
]

//id가 sese인 유저가 작성한 게시판 제목을 배열로 들고와보자.
const result = testArray.filter(x => x.user_id === 'sese').map(x=> x. title);
//[ 'js 질문이요', '제 질문에 답좀 부탁드려요' ]

결론

배열 내 요소의 특정 프로퍼티 값만 들고오고싶거나, 배열 내 요소들을 모두 콜백함수의 반환값들로 받고 싶을때 -> map
조건에 충족하는 요소들을 배열로 만들고 싶을 때는 -> filter

Reference

https://ordinary-code.tistory.com/8
https://velog.io/@tjdud0123/javascript-map-filter-%ED%95%A8%EC%88%98

😃 부족한 부분에 대한 피드백이 있다면 댓글 남겨주세요 !

0개의 댓글