filter, map, every

이재홍·2022년 6월 3일
0

Basic JS

목록 보기
3/18
post-thumbnail

실무에 나가게 되면 for문 보다는 map, filter 함수를 더 많이 사용하게 된다고 한다.
map, filter모두 배열의 내장함수 이기 때문에 사용할때는 배열과 함께 사용해야한다.
Array.prototype.map()
Array.prototype.filter()

map()메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환한다.

const classmate = ["철수","영희","훈이"]
classmate.map((item)=>(item+"어린이"))
=> (3)["철수어린이","영희어린이","훈이어린이"] 이렇게 됩니다.

map은 배열의 원소를 일괄적으로 변형시킬 때 사용하기 좋다.
map 안에서 사용되는 item은 classmate의 원소들이 들어갈 파라미터!(매게변수)이다!

객체가 원소인 배열에서도 map을 이용할 수 있다.

const classmate = [{name: "철수"},{name: "영희"},{name: "훈이"}]

//item.name => "철수","영희","훈이"
//school 속성을 일괄적으로 추가해주도록 하겠습니다.
classmate.map((item)=>({name : item.name + "어린이", school : "떡잎유치원"}))
=> (3)[
{name : "철수어린이",school : "떡잎유치원"},
{name : "영희어린이",school : "떡잎유치원"},
{name : "훈이어린이",school : "떡잎유치원"}

map 함수를 이용해 게시판리스트 같은 페이지를 데이터를 받아와 하드코딩으로 안그려줘도 된다.

{props.data?.fetchBoards.map((el, index) => (
            <LS.BoardsListLine key={el._id}>
              <LS.ColumnNumber>{index + 1}</LS.ColumnNumber>
              <LS.ColumnTitle onClick={props.onClickTitle} id={el._id}>
                {el.title}
              </LS.ColumnTitle>
              <LS.ColumnWriter>{el.writer}</LS.ColumnWriter>
              <LS.ColumnLike>{el.likeCount}</LS.ColumnLike>
              <LS.ColumnDisLike>{el.dislikeCount}</LS.ColumnDisLike>
            </LS.BoardsListLine>
          ))}

filter

filter 는 이름 그대로 배열의 원소를 필터링 해주는 메서드이다.
filter는 필터링 할 조건으로 객체 혹은 배열의 각 원소를 검사하여 그 조건에 맞는 원소들만 결과값으로 도출해 준다!

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

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
const num = [1,2,3,4,5,6,7,8,9,10]
num.filter((item)=>(item<=8))
=> (8) [1, 2, 3, 4, 5, 6, 7, 8]

map과 filter의 결과물 차이점

→ map은 배열의 길이만큼 값이 나오지만, filter는 조건에 따라 배열의 길이보다 적게 나온다.

every

Array.prototype.every()
: every메서드는 배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트하고 Boolean 값을 반환!!

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// expected output: true

참고: 빈 배열에서 호출하면 무조건 true를 반환합니다!

구문은 map,filter와 같지만 출력되는 부분이 boolean 값이라는 차이가 있다.

0개의 댓글