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

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

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/Javascript] ํ•œ ๋ฒˆ๋งŒ ๋“ฑ์žฅํ•œ ๋ฌธ์ž || ์ฝ”๋”ฉํ…Œ์ŠคํŠธ

728x90
function solution(s) {
    const set = new Set(s.split(""));
    let result = [];
    Array(...set).map(v => {
        let reg = new RegExp(`[${v}]`, 'g');
        s.match(reg).length === 1 && result.push(v);
    })
    return result.sort().join("");
}

set์œผ๋กœ ๋งŒ๋“ค์–ด์„œ ์ค‘๋ณต๋˜์ง€ ์•Š์€ ์•ŒํŒŒ๋ฒณ์„ ํ•˜๋‚˜์”ฉ reg ๋ฌธ์œผ๋กœ match ํ•œ ํ›„, ๊ธธ์ด๊ฐ€ 1์ด๋ฉด ๊ฒฐ๊ณผ ๋ฐฐ์—ด์— ๋„ฃ์–ด์คฌ๋‹ค.

๊ทธ๋ฆฌ๊ณ  ๊ฒฐ๊ณผ ๋ฐฐ์—ด์„ ์•ŒํŒŒ๋ฒณ์ˆœ์œผ๋กœ sort ํ•ด์ค€ ํ›„ ๋ฌธ์ž์—ด๋กœ return ํ•ด์คŒ. 

 

โšก์ •๊ทœ์‹์— ๋ณ€์ˆ˜ ๋„ฃ๋Š” ๋ฒ•

const ๋ณ€์ˆ˜ = 'abc';
const regex = new RegExp(`[${๋ณ€์ˆ˜}]`, 'g');
console.log(regex) // /[abc]/g

 

 

 

 

 

์ƒ๊ฐ์ด ๋ฉ‹์กŒ๋˜ ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด)

function solution(s) {
    let res = [];
    for (let c of s) if (s.indexOf(c) === s.lastIndexOf(c)) res.push(c);
    return res.sort().join('');
}

=> ๋ฌธ์ž์˜ index๊ฐ€ ๋งˆ์ง€๋ง‰์œผ๋กœ ์ฐพ์€ ๋ฌธ์ž์˜ index์™€ ๊ฐ™์œผ๋ฉด ==> 1๊ฐœ ๋ฐ–์— ์—†๋Š” ๊ฒƒ! 

 

 

โšก for ... of

for...of ๋ช…๋ น๋ฌธ์€ ๋ฐ˜๋ณต๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด (Array, Map, Set, String, TypedArray, arguments ๊ฐ์ฒด ๋“ฑ์„ ํฌํ•จ)์— ๋Œ€ํ•ด์„œ ๋ฐ˜๋ณตํ•˜๊ณ  ๊ฐ ๊ฐœ๋ณ„ ์†์„ฑ๊ฐ’์— ๋Œ€ํ•ด ์‹คํ–‰๋˜๋Š” ๋ฌธ์ด ์žˆ๋Š” ์‚ฌ์šฉ์ž ์ •์˜ ๋ฐ˜๋ณต ํ›„ํฌ๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๋ฃจํ”„๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.

=> ๋‚ด๊ฐ€ set๋กœ ๋งŒ๋“  ํ›„ map ์„ ํ•ด์คฌ๋˜ ๊ฒƒ์„ ์ด๋ ‡๊ฒŒ ๊ฐ„๋‹จํ•œ ๋ฐฉ๋ฒ•์œผ๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ์—ˆ๋‹ค. 

const array1 = ['a', 'b', 'c'];

for (const element of array1) {
  console.log(element);
}

// Expected output: "a"
// Expected output: "b"
// Expected output: "c"

 

โšก for ... in

for...in๋ฌธ์€ ์ƒ์†๋œ ์—ด๊ฑฐ ๊ฐ€๋Šฅํ•œ ์†์„ฑ๋“ค์„ ํฌํ•จํ•˜์—ฌ ๊ฐ์ฒด์—์„œ ๋ฌธ์ž์—ด๋กœ ํ‚ค๊ฐ€ ์ง€์ •๋œ ๋ชจ๋“  ์—ด๊ฑฐ ๊ฐ€๋Šฅํ•œ ์†์„ฑ์— ๋Œ€ํ•ด ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค. (Symbol๋กœ ํ‚ค๊ฐ€ ์ง€์ •๋œ ์†์„ฑ์€ ๋ฌด์‹œํ•ฉ๋‹ˆ๋‹ค.)

for( ๋ณ€์ˆ˜ in ๊ฐ์ฒด)

=> ๊ฐ์ฒด์˜ ๋ชจ๋“  ์—ด๊ฑฐํ•  ์ˆ˜ ์žˆ๋Š” ํ”„๋กœํผํ‹ฐ์˜ ๊ฐœ์ˆ˜๋งŒํผ ๋ฐ˜๋ณต์ ์œผ๋กœ ์‹คํ–‰ํ•˜๊ณ ์ž ํ•˜๋Š” ์‹คํ–‰๋ฌธ. 

 

 

์ฐจ์ด์ :

for in ์€ ๊ฐ์ฒด์˜ ์—ด๊ฑฐ ๊ฐ€๋Šฅํ•œ ํ”„๋กœํผํ‹ฐ๋ฅผ ์ž„์˜์˜ ์ˆœ์„œ๋กœ ๋ฐ˜๋ณต

for of ๋Š” iterable ๊ฐ์ฒด๊ฐ€ ๋ฐ˜๋ณตํ•˜๋„๋ก ์ •์˜ํ•œ ๊ฐ’์„ ๋ฐ˜๋ณต

 

 

๊ฐ์ฒด์˜ property๊ฐ€ ํ•„์š”ํ•œ ๊ฒฝ์šฐ๋Š” ๋งŽ์ง€ ์•Š์œผ๋‹ˆ, ์ผ๋ฐ˜ ๋ฐฐ์—ด, ๋ฌธ์ž์—ด ๋“ฑ์—์„œ๋Š”  of ๋ฅผ ์“ด๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋˜๊ฒ ๋‹ค. 

 

 

์ฐธ์กฐํ•œ ๋ธ”๋กœ๊ทธ

https://developerntraveler.tistory.com/122

 

[JavaScript] ๋ฐ˜๋ณต๋ฌธ for of / for in ์‚ฌ์šฉ๋ฒ• ๊ทธ๋ฆฌ๊ณ  ์ฐจ์ด

โœ… for ... of The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. It invokes a custom iteration hook

developerntraveler.tistory.com

 

728x90
๋ฐ˜์‘ํ˜•