[Javascript] filter()

sin·2022년 1월 7일
0

we

목록 보기
1/3

💬 filter()

배열 내 원소를 하나씩 확인하며 기준(=callbackfunction)에 맞는 원소들만 골라오는 함수

  1. 값이 존재하는 인덱스만 호출
  2. 값이 없는 배열은 함수 실행이 안 됨
  3. 배열 값 변경이 안 됨
  4. callback 호출 후 배열을 수정해도 수정한 배열로 함수가 실행되지 않음
array.filter(callbackfunction, thisAgr)
array.filter((element, index, array), thisAgr)

callback function = 기준

  • element = 필수, 현재 배열의 요소
  • index = 선택, 현재 배열 요소의 인덱스(element의 인덱스)
  • array = 선택, 호출한 배열

thisAgr = 선택, callbackfunction을 시행할 때 this로 사용되는 값(=map 함수에서 사용될 this 값)

💬 filter 바로 사용

filter()를 바로 사용하는 방법

let arrays = [0,10,20,40,60,80,90];

let filteredarray = arrays.filter((value)=> value>30);
console.log(filteredarray);
// ===> [40, 60, 80, 90]

💬 함수 선언 후 filter 사용

callbackfunction으로 사용할 함수를 먼저 선언하고 나서, filter()에서 선언한 함수를 이용하는 방법

let arrays = [0, 10, 20, 40, 60, 80, 90]

function filter(value){
 return value>30;
}
let filteredarray = arrays.filter(filter)
console.log(filteredarray)
// ===> [40, 60, 80, 90]

💬 다른 예시

조건 여러 개 사용

let arrays = [0, 5, 14, 30, 53, 77, 92]

let filteredarray = arrays.filter((value)=> {
	if (value > 10 && value%2==0) {
    	return true;
        }
        
       return false;
      });
 console.log(filteredarray);
 // ===> [14, 30, 92]

또 다른 예시

let arrays = [
{name : 'apple', price : 1000},
{name : 'strawberry', price : 1500},
{name : 'chocolate', price : 1500}
]

let filteredarray = arrays.filter((food)=> {
	if (food.name === 'chocolate') {
    return true;
    }
    
    return false;
});
console.log(filteredarray);
// ===> [{name : 'chocolate', price : 1500}]
profile
배우는 중

0개의 댓글