๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐ŸŒŒ | WEB DEV/React

[React] 2-1. array state ์ •๋ ฌํ•˜๊ธฐ ( .sort()ํ™œ์šฉ)

by KASSID 2023. 5. 27.

๋ชฉ์ฐจ

    728x90

    ์ด์ „ ๊ธ€ โ–ผ

     

     

    array state๋ฅผ ์ •๋ ฌํ•˜๊ณ  ์‹ถ์„ ๋•Œ๋Š” ์–ด๋–ป๊ฒŒ ํ•ด์•ผํ• ๊นŒ?

    ๊ฐ€์žฅ ๋ณดํŽธ์ ์ธ ๋ฐฉ๋ฒ•์ธ sort()๋ฉ”์„œ๋“œ๋ฅผ ์ด์šฉํ•ด๋ณด์ž.

     

    1. sort() ํ™œ์šฉํ•˜์—ฌ array state ์ •๋ ฌํ•˜๊ธฐ

     

    let [music, setMusic] = useState(
        [{"type": "Rock", "title": "Summer", "singer": "The Volunteers", "thumbs": 0},
        {"type": "HipHop", "title": "๊ทธ ํ•ด ์—ฌ๋ฆ„", "singer": "์œ ํ† ", "thumbs": 0},
        {"type": "Dance", "title": "Hype Boy", "singer": "New Jeans", "thumbs": 0},
        {"type": "Rock", "title": "Mercurial", "singer": "์‹ค๋ฆฌ์นด๊ฒ”", "thumbs": 0},
        {"type": "Dance", "title": "Spicy", "singer": "aespa", "thumbs": 0},
        {"type": "HipHop", "title": "Circle", "singer": "Post Malone", "thumbs": 0},
        ])

     

    ๊ฒฐ๊ณผํ™”๋ฉด

    ์œ„์˜ array state์— ์ •์˜๋œ ์ˆœ์„œ๋Œ€๋กœ ๋ฆฌ์ŠคํŠธ๊ฐ€ ๋ Œ๋”๋ง๋œ ๋ชจ์Šต์ด๋‹ค.

     

    ์ด๋ฅผ ABC ๋ฒ„ํŠผ์„ ํ†ตํ•ด ๋…ธ๋ž˜์ œ๋ชฉ์˜ ์ด๋ฆ„์ˆœ์œผ๋กœ ์ •๋ ฌํ•ด๋ณด์ž!

     

    1) sort()

    arr.sort(๋น„๊ตํ•จ์ˆ˜)

    (1) ๋งค๊ฐœ๋ณ€์ˆ˜

    sort() ๋ฉ”์„œ๋“œ๋Š” ๋น„๊ตํ•จ์ˆ˜๋ฅผ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ „๋‹ฌ๋ฐ›๋Š”๋‹ค.

    ์ด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ array๋‚ด ์š”์†Œ๋ฅผ ์ •๋ ฌํ•˜๊ณ  ๋ฐ˜ํ™˜ํ•œ๋‹ค.

    ๋งŒ์•ฝ ์ƒ๋žต์ด ๋œ๋‹ค๋ฉด, ๊ฐ ์š”์†Œ๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜ํ•œ ํ›„ ์œ ๋‹ˆ์ฝ”๋“œ ํฌ์ธํŠธ ๊ฐ’์— ๋”ฐ๋ผ ์ •๋ ฌํ•œ๋‹ค.

     

    (2) ๋ฐ˜ํ™˜๊ฐ’

    ์ •๋ ฌ๋œ array

    ์ด๋•Œ ์ฃผ์˜ํ•  ์ ์€ ๋ณต์‚ฌ๋ณธ์„ ์ƒ์„ฑํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ ์›๋ณธ์„ ์ •๋ ฌํ•œ๋‹ค.

     

    (3) ๋น„๊ตํ•จ์ˆ˜

    arr.sort((a,b)=>{
      if(a๊ฐ€ b๋ณด๋‹ค ๋จผ์ € ์™€์•ผํ•˜๋Š” ๊ฒฝ์šฐ) return -1;
      if(a๊ฐ€ b๋ณด๋‹ค ๋‚˜์ค‘์— ์™€์•ผํ•˜๋Š” ๊ฒฝ์šฐ) return 1;
      return 0; //๋™๋“ฑํ• ๋•Œ 
    })

    ๋ฐ˜ํ™˜ ๊ฐ’์— ๋”ฐ๋ผ ์ •๋ ฌ์„ ์ง€์‹œํ•œ๋‹ค.

     

     

    2) ํ™œ์šฉํ•˜๊ธฐ

    <button onClick={()=>{
        let copy = [...music];
        copy = copy.sort((a,b)=>{
          if (a.title > b.title) return 1;
          if (a.title < b.title) return -1;
          return 0;
        });
        setMusic(copy);
        }}>
        <span>ABC</span>
    </button>

     

    music state๋ฅผ ๊นŠ์€ ๋ณต์‚ฌํ•œ ๋’ค sort()๋ฉ”์„œ๋“œ์— ํ•จ์ˆ˜๋ฅผ ์ „๋‹ฌํ•˜์—ฌ ์ •๋ ฌํ•˜์˜€๋‹ค.

     

    ์ œ๋ชฉ์„ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•  ๊ฒƒ์ด๋ฏ€๋กœ

    a.title์ด b.title ๋ณด๋‹ค ํฐ ๊ฒฝ์šฐ('z'๊ฐ€ 'a'๋ณด๋‹ค ์œ ๋‹ˆ์ฝ”๋“œ ํฌ์ธํŠธ๊ฐ€ ํผ) 1์„ returnํ•˜๊ณ 

    ๋ฐ˜๋Œ€์˜ ๊ฒฝ์šฐ -1์„ return ํ•˜์—ฌ ์ •๋ ฌํ•œ๋‹ค.

     

     

     

    ๊ฒฐ๊ณผํ™”๋ฉด

     

    ๋Œ“๊ธ€