[JS] filter

미야옹·2021년 3월 12일
0

Filter

filter함수는 이름과 같이, callback함수에 조건에 해당하는 모든 요소를 찾아 새로운 배열에 넣어주는 기능입니다.

array.filter(callbackfunction(value,index,array),this{
callback함수내용 return 조건;
});

위의 구문으로 사용이 가능하며, value는 array내의 현재값이며, index는 현재값의 인덱스, array는 돌아가는 본인 배열을 나타냅니다. this는 callback함수내에서 사용되는 this값입니다.

let arr = [1,2,3,4,5,6,7,8];
let arrFilter = arr.filter(function(value){
  return (value % 2 === 0);
});
console.log(arrFilter) // [2, 4, 6, 8]

위의 예시처럼 사용이 가능합니다.

객체에서도 사용이 가능합니다.

const cats = [
  { name : 'Lucky' , age : 2},
  { name : 'Vanilla', age : 1},
  { name : 'Latte', age : 1},
  { name : 'midSummer', age : 1}
]
const cat = cats.filter(function(value){
  return (value.age>1);
});

console.log(cat) = [{ name : 'lucky' , age 2 }];

해당 내용처럼 객체내의 키,데이터를 callback함수에 조건에 해당하는 데이터만 따로 저장이 가능합니다.

0개의 댓글