๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

ํ”„์—” ๊ณต๋ถ€/๐Ÿซง ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ณต๋ถ€

[์•Œ๊ณ ๋ฆฌ์ฆ˜ || ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋ฌธ์ž์—ด ๋‚ด ๋งˆ์Œ๋Œ€๋กœ ์ •๋ ฌํ•˜๊ธฐ

728x90
function solution(strings, n) {
    return(strings.sort((a, b) => {
        if (a[n] === b[n]) {
            if (a < b) return -1;
            if (a > b) return 1;
            if (a === b) return 0;
        } else {
            if (a[n] < b[n]) return -1;
            if (a[n] > b[n]) return 1;
        }
    }))
}

sort ์— ๋Œ€ํ•ด ์กฐ๊ธˆ ๋” ์ •ํ™•ํ•˜๊ฒŒ ๊ณต๋ถ€ํ•˜๊ฒŒ ๋œ ๋ฌธ์ œ.

sort ์— ์ „๋‹ฌ๋˜๋Š” ํ•จ์ˆ˜์˜ return ๊ฐ’์— ๋”ฐ๋ผ์„œ ์ˆœ์„œ๊ฐ€ ์ •๋ ฌ๋œ๋‹ค. 

๋น„๊ตํ•˜๋ ค๋Š” ๋ฌธ์ž๊ฐ€ ๊ฐ™์€ ๊ฒฝ์šฐ, ์‚ฌ์ „์ˆœ์œผ๋กœ ์•ž์„  ๋ฌธ์ž์—ด์„ ์•ž์ชฝ์— ๋ฐฐ์น˜ํ•˜๊ธฐ ์œ„ํ•ด, a[n] === b[n] ์„ ๋”ฐ๋กœ ๋งŒ๋“ค์—ˆ๋‹ค.

 

return strings.sort((s1, s2) => s1[n] === s2[n] ? s1.localeCompare(s2) : s1[n].localeCompare(s2[n]));

 

๊ทผ๋ฐ ์ด ๋ถ€๋ถ„๋“ค์„ ์ƒ๋žตํ•˜๊ณ  ์ด๋ ‡๊ฒŒ ๊ฐ„๋‹จํžˆ ๋‚˜ํƒ€๋‚ธ ํ’€์ด๊ฐ€ ์žˆ์—ˆ๋”ฐ.

localCompare ์ฒ˜์Œ ๋ดค๋‹ค..!

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

 

String.prototype.localeCompare() - JavaScript | MDN

localeCompare() ๋ฉ”์„œ๋“œ๋Š” ์ฐธ์กฐ ๋ฌธ์ž์—ด์ด ์ •๋ ฌ ์ˆœ์œผ๋กœ ์ง€์ •๋œ ๋ฌธ์ž์—ด ์•ž ํ˜น์€ ๋’ค์— ์˜ค๋Š”์ง€ ๋˜๋Š” ๋™์ผํ•œ ๋ฌธ์ž์—ด์ธ์ง€ ๋‚˜ํƒ€๋‚ด๋Š” ์ˆ˜์น˜๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

developer.mozilla.org

 

localeCompare() ๋ฉ”์„œ๋“œ๋Š” ์ฐธ์กฐ ๋ฌธ์ž์—ด์ด ์ •๋ ฌ ์ˆœ์œผ๋กœ ์ง€์ •๋œ ๋ฌธ์ž์—ด ์•ž ํ˜น์€ ๋’ค์— ์˜ค๋Š”์ง€ ๋˜๋Š” ๋™์ผํ•œ ๋ฌธ์ž์—ด์ธ์ง€ ๋‚˜ํƒ€๋‚ด๋Š” ์ˆ˜์น˜๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
localeCompare(compareString)
localeCompare(compareString, locales)
localeCompare(compareString, locales, options)
compareStringreferenceStr๊ฐ€ ๋น„๊ต๋˜๋Š” ๋ฌธ์ž์—ด.locales์™€ options์ด๋Ÿฌํ•œ ์ธ์ˆ˜๋Š” ํ•จ์ˆ˜์˜ ๋™์ž‘์„ ์‚ฌ์šฉ์ž ์ •์˜ํ•˜์—ฌ ์‘์šฉ ํ”„๋กœ๊ทธ๋žจ์—์„œ ํฌ๋งท ๊ทœ์น™์„ ์‚ฌ์šฉํ•  ์–ธ์–ด๋ฅผ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค. "locales"์™€ "options"์˜ ์ธ์ž๋ฅผ ๋ฌด์‹œํ•˜๋Š” ๊ตฌํ˜„์—์„œ๋Š” ์‚ฌ์šฉ๋˜๋Š” ๋กœ์ผ€์ผ๊ณผ ๋ฐ˜ํ™˜๋˜๋Š” ๋ฌธ์ž์—ด์˜ ํ˜•์‹์€ ์™„์ „ํžˆ ๊ตฌํ˜„์— ์˜์กดํ•ฉ๋‹ˆ๋‹ค. 

referenceStr๊ฐ€ compareString ์ „ ํ˜น์€ ๋’ค์— ์˜ค๋Š”์ง€ ๋˜๋Š” ๋™๋“ฑํ•œ์ง€๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์ •์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
compareString ์ „์— referenceStr์ด ์˜ค๋ฉด ์Œ์ˆ˜
compareString ๋’ค์— referenceStr์ด ์˜ค๋ฉด ์–‘์ˆ˜
๋™๋“ฑํ•œ ๊ฒฝ์šฐ 0 ์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

 

728x90
๋ฐ˜์‘ํ˜•