๋ฐฐ์ด ๋ด์์ ์ค๋ณต ๊ฐ์ ์ถ์ถํ๋ ๋ฐฉ๋ฒ์ด๋ค.
์๋ฅผ ๋ค์ด [1, 1, 2, 3, 5] ๋ฐฐ์ด์์ ์ค๋ณต ๊ฐ์ธ [1] ์ ๊ตฌํ๋ ๋ฐฉ๋ฒ์ด๋ค.
์ค๋ณต ๊ฐ์ ๊ตฌํด์ผ ํ๋ ๋์ ๋ฐฐ์ด์ด ๊ฐ์ฒด๋ฅผ ์์๋ก ๊ฐ๋ ๋ฐฐ์ด์ด๋ผ๋ฉด ๊ฐ์ฒด์์ ์ค๋ณต์ ๊ฒ์ฌํ ๋์๋ง ์ถ์ถํ๋ค.
(์ค๋ณต์ด ๊ฐ์ฒด ๋ด ๊ฐ์ด ์๋๋ผ ๊ฐ์ฒด ์์ฒด๋ผ๋ฉด JSON.stringify() ๋ฑ์ผ๋ก ๋ณํํ์ฌ ํ์ธํด์ผ ํ๋ค.)
// ๋ฐ์ดํฐ
let arr = [{
"name": "ํ๊ธธ๋",
"phoneNumber": "010-1111-1111"
}, {
"name": "๊น๊ธธ๋",
"phoneNumber": "010-2222-2222"
}, {
"name": "๊ณ ๊ธธ๋",
"phoneNumber": "010-3333-3333"
}, {
"name": "์๊ธธ๋",
"phoneNumber": "010-1111-1111"
}, {
"name": "์๊ธธ๋",
"phoneNumber": "010-4444-4444"
}, {
"name": "์ฌ๊ธธ๋",
"phoneNumber": "010-5555-5555"
}];
// ์ ํ๋ฒํธ๋ง ์ถ์ถ
// ["010-1111-1111", "010-2222-2222", "010-3333-3333", "010-1111-1111", "010-4444-4444", "010-5555-5555"]
let phoneNumbers = arr.map(x => x.phoneNumber);
CASE 01) indexOf()
function findDuplication(arr) {
return arr.filter((item, index) => arr.indexOf(item) !== index);
}
console.log(findDuplication(phoneNumbers)); // ["010-1111-1111"]
CASE 02) Set
function findDuplication(arr) {
const uniqueSet = new Set(arr);
const filtered = arr.filter(item => {
if (uniqueSet.has(item)) {
uniqueSet.delete(item);
} else {
return item;
}
});
return [...new Set(filtered)]
}
console.log(findDuplication(phoneNumbers)); // ["010-1111-1111"]
'๊ฐ๋ฐ > Javascript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์๋ฐ์คํฌ๋ฆฝํธ ์ ์ฉํ ํจ์ ๋ชจ์ (0) | 2022.08.29 |
---|---|
javascript ๊ฐ์ฒด ํค ์ด๋ฆ ๋ณ๊ฒฝ (0) | 2022.07.08 |
javascript byte ์ ๊ณ์ฐ (0) | 2022.06.21 |
Object.freeze ๊ฐ์ฒด ๋๊ฒฐ / ๊ฐ์ฒด ์ฝ๊ธฐ ์๋ (0) | 2022.05.12 |
ES6 Syntax (0) | 2022.05.03 |
๋๊ธ