Javascript | filter vs map vs every

space's pace·2022년 6월 28일
0

Javascript

목록 보기
6/20
post-thumbnail

Javascript에서 유용하게 사용할 수 있는 배열 함수들이다.
알고리즘 + 코드 리팩토링을 위해 메서드는 잘 활용하면 정말정말 좋다
그 중에서 가장 많이 쓰이고 비슷한 세 가지를 비교해보려 한다.

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"]

Syntax

arr.filter(callback(element[, index[, array]])[, thisArg])

설명

filter()는 배열 내 각 요소에 대해 한 번 제공된 callback 함수를 호출해, callback이 true로 강제하는 값을 반환하는 모든 값이 있는 새로운 배열을 생성한다.


1 . `callback`은 할당된 값이 있는 배열의 인덱스에 대해서만 호출된다 2. 삭제됐거나 값이 할당된 적이 없는 인덱스에 대해서는 호출x 3. 테스트를 통과하지 못한 배열 요소는 그냥 건너뛰며, 새로운 배열에 포함x

map과 filter의 차이점

map은 배열의 길이만큼 값이 나오지만,
filter는 조건에 따라 배열의 길이보다 적거나 같게 나온다.
또한 filter는 배열의 원소를 변형하여 반환할 수 없다.

map

: 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

Syntax

arr.map(callback(currentValue[, index[, array]])[, thisArg])

const classmate = ["   ","   ","   "]
classmate.map((item)=>(item+" "))
=> (3)[" "," "," "] .

기본형식은 ((el) => ()) 임

const classmate = [
        {name: "진구"},
        {name: "비실이"},
        {name: "퉁퉁이"}]
//item.name => "진구","비실이","퉁퉁이"
//school
classmate.map((item)=>({name : item.name + "어린이",
                      school : "떡잎유치원"}))
=> (3)[
{name : "진구어린이",school : "떡잎유치원"},
{name : "비실이어린이",school : "떡잎유치원"},
{name : "퉁퉁이어린이",school : "떡잎유치원"}
]

배열은 map(( ) => ( ))
배열안의 객체는 map(( ) => ({ }))
객체가 들어간 배열은 중괄호{ }로 감싸주어야 한다.

화살표 함수에서 소괄호 생략이 가능하다.
다만 한줄짜리 코드여야한다.

소괄호 생략이 불가능한 경우
리턴값이 객체인 경우

every

:배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트한다. Boolean 값을 반환

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

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

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

Syntax

// 화살표 함수
every((element) => { ... } )
every((element, index) => { ... } )
every((element, index, array) => { ... } )

// 콜백 함수
every(callbackFn)
every(callbackFn, thisArg)

// 인라인 콜백 함수
every(function callbackFn(element) { ... })
every(function callbackFn(element, index) { ... })
every(function callbackFn(element, index, array){ ... })
every(function callbackFn(element, index, array) { ... }, thisArg)

Mdn 참고 https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/every

profile
블로그 이사 준비중!

0개의 댓글