Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reduce를 filter처럼 써보기 #35

Open
HOJOON07 opened this issue Dec 2, 2023 · 0 comments
Open

reduce를 filter처럼 써보기 #35

HOJOON07 opened this issue Dec 2, 2023 · 0 comments

Comments

@HOJOON07
Copy link
Owner

HOJOON07 commented Dec 2, 2023

예전에 블로그를 탐방하다가 좋은 글을 본적이 있어서 제 블로그에 글을 썼던 경험이 생각나서 적어봤습니다.

const { a, b, c, d } = types.reduce(
    (acc, type) => {
      switch (types.type) {
        case 'a':
          acc.a.push(type);
          break;
        case 'b':
          acc.b.push(type);
          break;
        case 'c':
          acc.c.push(type);
          break;
        case 'd':
          acc.d.push(type);
          break;
        default:
          acc.all_types.push(type);
          break;
      }
      return acc;
    },
    {
      a: [],
      b: [],
      c: [],
      d: [],
    } as Record<string, Types[]>,
  );

코드가 길어졌을 수도 있다고 생각하지만 같은 배열을 4번이나 반복하던 것을 한번으로 줄이고 로직만 따로 분리하면 유용하게 쓸 수 있습니다.!!

추가로 객체를 반복문처럼 돌리기 위해서는

const obj = {
 a: "1",
 b: "2",
 c: "3"
};

console.log(Object.entries(obj))
// 3) [Array(2), Array(2), Array(2)]

0: (2) ["a", 1]
1: (2) ["b", 2]
2: (2) ["c", 3]

리액트에서

 {Object.entries(types).map(([name, type]) => (
      <>
        <h3>{name}</h3>
        <ul className="type">
          {type.map((item) => <PlayerCard key={item.key} />)}
        </ul>
      </>
    ))}

원래 코드라면

<h3>a</h3>
<ul className="list">
	{list.map((name) => <PlayerCard key={name.key} />))} 		
</ul>
<h3>b</h3>
<ul className="list">
	{list.map((name) => <PlayerCard key={name.key} />))} 		
</ul>
<h3>c</h3>
<ul className="list">
	{list.map((name) => <PlayerCard key={name.key} />))} 		
</ul>        
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant