new Set([iterable]);
์ฝ์ ์์๋๋ก ์์ ์ํ, Set์๋ ์ค๋ณต๋ ๊ฐ์ด ๋ค์ด์ฌ ์ ์๋ค.
const setTest = new Set();
setTest.add(1); // {1}
setTest.add(2); // {1, 2}
// 1์ addํด๋ set์ 1์ด ์์ด์ ๋ฌด์๋จ
setTest.add(1); // {1, 2}
arr.filter(callback(element[, index[, array]])[, thisArg])
callback : ์์๋ฅผ ๊ฑธ๋ฌ์ฃผ๋ ํจ์, ์กฐ๊ฑด์ ๋ง์ง ์์ผ๋ฉด ์ญ์
element : ์ฒ๋ฆฌํ ํ์ฌ ์์
index(option) : ์ฒ๋ฆฌํ ํ์ฌ ์์์ ์ธ๋ฑ์ค
const filterArr = [1, 2, 3, 4, 5];
filterArr.filter(function(v){
return v > 3; // [4, 5]
});
// ํ์ดํ ํจ์
filterArr.filter(v => v > 3); // [4, 5]
๋ฌธ์์ด, ๋ฐฐ์ด ์ค๋ณต ์ ๊ฑฐํ๊ธฐ
/* ๋ฌธ์์ด ์ค๋ณต ์ ๊ฑฐ : [...new Set(str)].join('') */
const str = 'abcaabbd';
// new Set์ผ๋ก ์ค๋ณต ์ ๊ฑฐ
new Set(str); // {"a", "b", "c", "z"}
[...new Set(str)]; // ["a", "b", "c", "z"]
[...new Set(str)].join(''); // "abcz"
// ๊ธฐ์กด str์ด ์ํฅ๋ฐ์ง ์๋๋ค.
console.log(str); // "abcaabbd"
/* ๋ฐฐ์ด ์ค๋ณต ์ ๊ฑฐ : 1. [...new Set(arr)], 2. Array.prototype.filter() */
const arr = ['a', 'b', 'c', 'a', 'a', 'b', 'b', 'd'];
// 1. [...new Set(arr)]
[...new Set(arr)] // ["a", "b", "c", "d"]
// ๊ธฐ์กด arr๊ฐ ์ํฅ๋ฐ์ง ์๋๋ค.
console.log(arr); // ["a", "b", "c", "a", "a", "b", "b", "d"]
// 2. Array.prototype.filter()
// indexOf๋ ์ฒ์์ผ๋ก ๋ฐ๊ฒฌํ a์ index ์์น๋ง ๋ฐํํ๊ธฐ ๋๋ฌธ์,
// ๊ทธ ๋ค์์ a๋ฅผ ์ํํ ๋๋ indexOf(v)์ i๊ฐ ๋ง์ง ์๋๋ค.
arr.filter((v, i) => arr.indexOf(v) === i); // ["a", "b", "c", "d"]
// ๊ธฐ์กด arr๊ฐ ์ํฅ๋ฐ์ง ์๋๋ค.
console.log(arr); // ["a", "b", "c", "a", "a", "b", "b", "d"]