๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Frontend/JavaScript

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] ๋ฐฐ์—ด์˜ ํŠน์ • ์ธ๋ฑ์Šค๋ฅผ ์ œ๊ฑฐํ•˜๊ฑฐ๋‚˜ ํŠน์ • ๋ฒ”์œ„๋งŒ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜, filter, splice, slice

by YWTechIT 2021. 7. 23.
728x90

๐Ÿ“ ๋ฐฐ์—ด์˜ ํŠน์ • ์ธ๋ฑ์Šค๋ฅผ ์ œ๊ฑฐํ•˜๊ฑฐ๋‚˜ ํŠน์ • ๋ฒ”์œ„๋งŒ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜, filter, splice, slice

์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ๋ฅผ ํ’€๋‹ค๊ฐ€ ๋ฐฐ์—ด์˜ ํŠน์ • ์›์†Œ๋‚˜ ์ธ๋ฑ์Šค๋ฅผ ์‚ญ์ œํ•˜๊ฑฐ๋‚˜ ํŠน์ • ๋ฒ”์œ„๋ฅผ ์ œ๊ฑฐํ•˜๊ณ  ์‹ถ์–ด MDN์„ ์ฐพ์•„๋ณด๋‹ˆ๊นŒ ์—ฌ๋Ÿฌ๊ฐ€์ง€ ํ•จ์ˆ˜๊ฐ€ ์กด์žฌํ–ˆ๋‹ค. ์ƒํ™ฉ๋งˆ๋‹ค ๋‹ค๋ฅด์ง€๋งŒ ๋กœ์ง์„ ๊ตฌํ˜„ํ•  ๋•Œ ๋‹ค์Œ์˜ ์„ ํƒ์ง€๋ฅผ ๋ณด๊ณ  ๊ณจ๋ผ์„œ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

 

์›๋ณธ ๋ฐฐ์—ด์„ ๋ณ€๊ฒฝํ•˜๊ณ  ์‹ถ์ง€์•Š๊ณ  ํŠน์ • ์ธ๋ฑ์Šค๋ฅผ ์ œ๊ฑฐํ•˜๊ณ  ์‹ถ์„ ๋•Œ(์ƒˆ๋กœ์šด ๋ณ€์ˆ˜์— ์„ ์–ธํ•˜๊ณ  ์‹ถ์„ ๋•Œ)

  1. filter: ์ฃผ์–ด์ง„ ํ•จ์ˆ˜์˜ ํ…Œ์ŠคํŠธ๋ฅผ ํ†ต๊ณผํ•˜๋Š” ๋ชจ๋“  ์š”์†Œ๋ฅผ ๋ชจ์•„ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด๋กœ ๋ฐ˜ํ™˜ํ•œ๋‹ค. arr.filter(callback(element[, index ?[, array ?]])[, thisArg ?])

์›๋ณธ ๋ฐฐ์—ด์„ ๋ณ€๊ฒฝํ•˜๊ณ  ํŠน์ • ์ธ๋ฑ์Šค๋ฅผ ์ œ๊ฑฐํ•˜๊ณ  ์‹ถ์„ ๋•Œ(์ƒˆ๋กœ์šด ๋ณ€์ˆ˜์— ์„ ์–ธํ•˜๊ณ  ์‹ถ์„ ์•Š์„ ๋•Œ)

  1. splice: ๋ฐฐ์—ด์˜ ๊ธฐ์กด ์š”์†Œ๋ฅผ ์‚ญ์ œ ๋˜๋Š” ๊ต์ฒดํ•˜๊ฑฐ๋‚˜ ์ƒˆ ์š”์†Œ๋ฅผ ์ถ”๊ฐ€ํ•˜์—ฌ ๋ฐฐ์—ด์˜ ๋‚ด์šฉ์„ ๋ณ€๊ฒฝํ•œ๋‹ค. (array.splice(start, delete ?, item ?))

์›๋ณธ ๋ฐฐ์—ด์„ ๋ณ€๊ฒฝํ•˜๊ณ  ์‹ถ์ง€ ์•Š๊ณ  ํŠน์ • ๋ฒ”์œ„๋ฅผ ์ž˜๋ผ๋‚ด๊ณ  ์‹ถ์„ ๋•Œ

  1. slice: ์–ด๋–ค ๋ฐฐ์—ด์˜ begin๋ถ€ํ„ฐ end๊นŒ์ง€(end๋Š” ๋ฏธํฌํ•จ)์— ๋Œ€ํ•œ ์–•์€ ๋ณต์‚ฌ(shallow copy)๋ณธ์„ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด ๊ฐ์ฒด๋กœ ๋ฐ˜ํ™˜์‹œํ‚จ๋‹ค. arr.slice(begin ?, end ?)

 

์ •์˜๋งŒ ๋ด์„œ๋Š” ์ž˜ ์ดํ•ด๊ฐ€ ์•ˆ ๋˜๋‹ˆ๊นŒ ์‰ฝ๊ฒŒ ์˜ˆ๋ฅผ ๋“ค์–ด๋ณด์ž. ๋‹ค์Œ์˜ arr์—์„œ ๋‚˜๋Š” arr[2]์˜ ๊ฐ’์„ ์ œ๊ฑฐํ•˜๊ณ , arr์˜ [1 : 3]๋ฒ”์œ„๋งŒ ์ž๋ฅด๊ณ  ์‹ถ๋‹ค๊ณ  ํ•  ๋• ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

 

const arr = [0, 2, 1, 6]

// filter
const filterArr = arr.filter((item) => item !== arr[2])
console.log(filterArr)
๐Ÿ‘‰๐Ÿฝ [0, 2, 6]

// splice
arr.splice(2)
console.log(arr)
๐Ÿ‘‰๐Ÿฝ [0, 2, 6]

// slice
const sliceArr = arr.slice(1, 3)
console.log(sliceArr)
๐Ÿ‘‰๐Ÿฝ [2, 1]

 

์—ฌ๋‹ด์œผ๋กœ slice๋Š” ์›๋ณธ ๊ฐ์ฒด๋ฅผ ์–•์€ ๋ณต์‚ฌ(shallowCopy)๊นŒ์ง€ ๊ฐ€๋Šฅํ•œ๋ฐ, ์ •๋ง ์–•์€ ๋ณต์‚ฌ(shallowCopy) ๊นŒ์ง€๋งŒ ๋˜๋Š”์ง€ ์‹คํ—˜ํ•ด๋ดค๋‹ค. ์‹คํ—˜ ๊ฒฐ๊ณผ depth = 2์ธ ๊ฐ’์„ ๋ณ€๊ฒฝ ์‹œ ์›๋ณธ ๊ฐ’๋„ ๋ณ€๊ฒฝ๋œ ๊ฒƒ์œผ๋กœ ๋ณด์•„ ๊ฒฐ๋ก ์ ์œผ๋กœ ์–•์€๋ณต์‚ฌ๊นŒ์ง€๋งŒ ๊ฐ€๋Šฅํ–ˆ๋‹ค.

// depth = 1์ผ ๋•Œ slice
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const copyArr = arr.slice();
arr[2] = -9999

console.log(copyArr)
๐Ÿ‘‰๐Ÿฝ [1, 2, 3, 4, 5, 6, 7, 8, 9];

// depth = 2์ผ ๋•Œ slice
const arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const copyArr = arr.slice();
arr[0][2] = -9999

console.log(copyArr)
๐Ÿ‘‰๐Ÿฝ [[1, 2, -9999], [4, 5, 6], [7, 8, 9]];
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€