[JS] Arr.filter() - 댓글 제거기능 구현중 활용

hyeonze·2021년 12월 23일
0

Array.prototype.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 handleDelete = e => {
    const { id } = e.target.parentNode.parentNode;
    addedCommentVal = addedCommentVal.filter(el => el.id !== Number(id));
    setCommentVal(addedCommentVal);
  };

주의할 점

콜백함수는 return값이 있어야 함. 화살표 함수를 사용하며 생략된 것.

기타

콜백함수는 filter함수의 첫 번째 인자임. 콜백함수도 인자 세개(el, i, arr)를 받을 수 있음.
filter인자의 두 번째 인자로 콜백 내에서 this로 사용할 값을 지정할 수 있음.

profile
Advanced thinking should be put into advanced code.

0개의 댓글

관련 채용 정보