배열 내 원소를 하나씩 확인하며 기준(=callbackfunction)에 맞는 원소들만 골라오는 함수
array.filter(callbackfunction, thisAgr)
array.filter((element, index, array), thisAgr)
callback function = 기준
thisAgr = 선택, callbackfunction을 시행할 때 this로 사용되는 값(=map 함수에서 사용될 this 값)
filter()를 바로 사용하는 방법
let arrays = [0,10,20,40,60,80,90];
let filteredarray = arrays.filter((value)=> value>30);
console.log(filteredarray);
// ===> [40, 60, 80, 90]
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}]