๐Ÿฅซ concat

์œ ๊ด€ํฌยท2022๋…„ 4์›” 23์ผ
0
post-thumbnail

indexOf(), filter()

indexOf() ํ•จ์ˆ˜๋Š”, ๋ฐฐ์—ด์—์„œ ํŠน์ •๊ฐ’์ด ์ฒ˜์Œ์œผ๋กœ ๋‚˜ํƒ€๋‚˜๋Š” index๋ฅผ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค.

filter() ํ•จ์ˆ˜๋Š” ํŠน์ • ์กฐ๊ฑด์— ๋ถ€ํ•ฉํ•˜๋Š” ๋ฐฐ์—ด์˜ ๋ชจ๋“  ๊ฐ’์„ ๋ฐฐ์—ด ํ˜•ํƒœ๋กœ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค.

const dupArr = [1, 2, 3, 1, 2];
const uniqueArr = dupArr.filter((element, index) => {
return dupArr.indexOf(element) === index;
});
document.writeln(Array.isArray(uniqueArr));
document.writeln(uniqueArr);

์œ„ ์˜ˆ์ œ์—์„œ

dupArr.filter(callback);

filter() ํ•จ์ˆ˜๋Š”

dupArr์˜ ์›์†Œ๋“ค์„ callback ํ•จ์ˆ˜๋กœ ์ „๋‹ฌํ•˜์—ฌ

๊ฐ ์›์†Œ๋“ค์ด callback ํ•จ์ˆ˜์— ์ •์˜๋œ ๊ธฐ์ค€์— ๋ถ€ํ•ฉํ•˜๋Š”์ง€ ๊ฒ€์‚ฌํ•˜๊ณ ,

๊ฒ€์‚ฌ ๊ฒฐ๊ณผ๊ฐ€ true๋ฅผ ๋ฆฌํ„ดํ•˜๋Š” ์›์†Œ์„ ๋ชจ์•„์„œ ๋ฐฐ์—ด ํ˜•ํƒœ๋กœ ๋ฆฌํ„ด(uniqueArr) ํ•ฉ๋‹ˆ๋‹ค.

dupArr.indexOf(element) === index;

filter() ํ•จ์ˆ˜๋กœ ์ „๋‹ฌ ๋œ callback ํ•จ์ˆ˜๋Š”
๊ฒ€์‚ฌํ•˜๊ณ  ์žˆ๋Š” ๊ฐ’(element)์ด ๋ฐฐ์—ด(dupArr)์—์„œ ๊ฐ€์žฅ ์ฒ˜์Œ์œผ๋กœ ๋‚˜ํƒ€๋Š” index์™€
๊ฒ€์‚ฌํ•˜๊ณ  ์žˆ๋Š” ์›์†Œ์˜ index์™€ ๋น„๊ตํ•˜์—ฌ
๊ฐ™์„ ๊ฒฝ์šฐ์—๋งŒ true๋ฅผ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค.

์œ„์˜ ์˜ˆ์ œ์—์„œ dupArr์˜ ๊ฐ’์ด ์ˆœ์„œ๋Œ€๋กœ ์ „๋‹ฌ๋˜๋ฉด
'dupArr.indexOf(element) === index' ๊ตฌ๋ฌธ์€
true, true, true, false, false ๋ฅผ ์ˆœ์„œ๋Œ€๋กœ ๋ฆฌํ„ดํ•˜์—ฌ
์ค‘๋ณต๋˜๋Š” ๊ฐ’์ด ์ฒซ๋ฒˆ์งธ๋กœ ๋‚˜ํƒ€๋‚˜๋Š” ๊ฒฝ์šฐ์—๋งŒ filter ํ•จ์ˆ˜์—์„œ ๊ฑธ๋Ÿฌ์ง€๋„๋ก ํ•˜์˜€์Šต๋‹ˆ๋‹ค.

Set ๊ฐ์ฒด๋ฅผ ํ™œ์šฉํ•˜์—ฌ ๋ฐฐ์—ด์˜ ์ค‘๋ณต ์›์†Œ ์ œ๊ฑฐํ•˜๋Š” ๋ฒ•

Set์€ ES6์—์„œ ๋“ฑ์žฅํ•œ ์ƒˆ๋กœ์šด ๋ฐ์ดํ„ฐ object์ด๋‹ค. Set์€ uniqueํ•œ ๊ฐ’๋งŒ ์ €์žฅํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•˜๊ธฐ ๋•Œ๋ฌธ์— Array์— ๋„ฃ๊ฒŒ ๋˜๋ฉด ์ค‘๋ณต๋˜๋Š” ๊ฐ’์ด ์‚ฌ๋ผ์ง„๋‹ค.

const dupArr = [1, 2, 3, 1, 2];
const set = new Set(dupArr);
const uniqueArr = [...set];
console.log(uniqueArr) // [1, 2, 3]

์ค‘๋ณต๊ฐ’์ด ์žˆ๋Š” ๋ฐฐ์—ด์„ Set๊ฐ์ฒด๋กœ ๋งŒ๋“ค๋ฉด ์ค‘๋ณต์ด ์ œ๊ฑฐ๊ฐ€ ๋˜๋Š”๋ฐ, ์ด๋ฅผ ๋‹ค์‹œ Spread Oprator๋ฅผ ํ™œ์šฉํ•˜์—ฌ ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜ํ•˜๋ฉด ์ฒ˜์Œ ๋ฐฐ์—ด์—์„œ ์ค‘๋ณต๊ฐ’์ด ์ œ๊ฑฐ๋œ ์ƒํƒœ๊ฐ€ ๋œ๋‹ค. Spread Operator ๋ง๊ณ  Array.from์œผ๋กœ ๋ฐฐ์—ด๋กœ ๋ณ€๊ฒฝํ•ด๋„ ๊ฐ™์€ ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜จ๋‹ค.

const dupArr = [1, 2, 3, 1, 2];
const set = new Set(dupArr);
const uniqueArr = Array.from(set);
console.log(uniqueArr) // [1, 2, 3]

profile
์•ˆ๋…•ํ•˜์„ธ์š”~

0๊ฐœ์˜ ๋Œ“๊ธ€