[Study] FE/React

[포스코x코딩온] React 04 Map () & filter()

stop-zero 2023. 4. 23. 21:07
더보기

🙌  자바스크립의 메서드 map, filter, concat 등을 먼저 복습하고 react에서 응용하여 실습 코드를 작성했다. 

배운 메서드만 적용하는 것이 아닌, 실습 코드에서 필요한 'Enter 입력' & '공백 입력x' & 'input 값 초기화'까지 추가했다. 

JavaScript 메서드 복습

map() 함수

메서드는 배열 내의 모든 요소 각각에 대한 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환한다. 

필요에 따라 반복문처럼 사용 가능

arr.map(callbackFunc, [Arg])

callbackFunc : 새로운 배열의 요소를 생성하는 함수로  3개의 인수(currentValue, index, array)를 가질 수 있다. [Arg]는 생략 가능한 것으로 callbackFunc에서 사용할 this 객체이다. 

  • currentValue : 원소 값
  • index : 인덱스 위치
  • array : 현재 순회하고 있는 배열 전체
// map()
const items = list.map((txt, id, arr) => {
  console.log('txt: ', txt); //원소값
  console.log('id: ', id); //인덱스 위치
  console.log('arr: ', arr); //현재 순회하고 있는 배열 전체

  return `${id}위치에 ${txt}원소가 있음`;
});

console.log('items >> ', items);

 

filter()

filter()의 인자로 넘겨지는 callback 함수의 조건을 통과하는 요소를 모아 새로운 배열을 생성한다. (ex. 조건을 통과하는 요소를 모아 true면 요소 유지, false면 버림)

const animals = ['dog', 'cat', 'rabbit'];

const newAnimalse = animals.filter((animal) => {
  return animal.length > 3;
});
console.log(newAnimalse); //[ 'rabbit' ]

const newAnimalse2 = animals.filter((animal) => {
  return animal.includes('a');
});
console.log(newAnimalse2); //[ 'cat', 'rabbit' ]

filter() 함수를 사용하여 배열에서 원하는 값을 삭제하는 코드도 구현 가능하다. 

 

concat() : 배열 합치기

const aaa = ['a', 'b', 'c'];
const bbb = ['d', 'e', 'f'];

console.log(aaa.concat(bbb)); //[ 'a', 'b', 'c', 'd', 'e', 'f' ]

 

map(), filter 실습 코드

import { useState } from 'react';

const StudyMap = () => {
  // text state : 리스트에 대한 상태
  const [text, setText] = useState([]);

  // inputText state : input 에 넣는 값에 대한 상태
  const [inputText, setInputText] = useState('');

  const addText = () => {
    // 공백 입력 x
    // trim() 메소드로 공백 제거 하고 
    // 글자 수가 0인 경우 함수 종료.
    if (!inputText.trim().length) {
      return;
    }

    // concat() : 메서드는 인자로 주어진 값을 기존 배열에 합쳐서 새 배열로 반환
    const newText = text.concat({
      id: text.length + 1,
      alpha: inputText,
    });
    setText(newText);
    setInputText('');
  };

  // filter 적용
  // deleteText : 
  // id 매개변수와 일치하지 않는 id 속성을 가진 text 배열의 요소를 삭제
  const deleteText = (id) => {
    const newText = text.filter((obj) => obj.id !== id);
    setText(newText);
  };

  // Enter 입력
  const activeEnter = (e) => {
    if (e.key == 'Enter') addText();
  };

  return (
    <>
      <input
        type="text"
        value={inputText}
        onChange={(e) => {
          setInputText(e.target.value);
        }}
        onKeyDown={(e) => activeEnter(e)}
      />
      <button onClick={addText}>추가</button>
      <ol>
        {text.map((value) => (
          <h5 key={value.id} onDoubleClick={() => deleteText(value.id)}>
            {value.alpha}
          </h5>
        ))}
      </ol>
    </>
  );
};

export default StudyMap;

map() 메서드 적용

새로운 배열을 반환하는 map은 text.map()에서 text 배열의 각 요소를 생성하고 이를 화면에 렌더링한다. 

 

concat() 메서드 적용 newText

이 코드는 inputText와 함께 id 속성이 자동으로 할당된 새로운 객체를 생성하고, 이를 기존 text 배열과 병합하여 새로운 배열을 만드는 newText 변수를 생성한다. 

그다음 setText(newText)를 호출해 text 배열을 newText로 변경한다. 

마지막 setInutText('')으로 다음 입력을 위해 input값을 비워준다. 

 

filter () 메서드 적용  deleteText

매개변수 id와 id 속성을 가진 text 배열의 요소를 삭제한다. 

filter() 메서드는 text 배열 요소를 반복하면서 obj.id !== id 조건을 만족하는 요소만 가지고 newText를 생성한다. 이 말은 즉, 더블 클릭된 id랑 다른 애들만 newText에 들어간다.

<h5 key={value.id} onDoubleClick={() => deleteText(value.id)}>
{value.alpha}
</h5>

그리고 setText로 text 배열을 newText로 대체한다.