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

javascript ๋ฐฐ์—ด ๋‚ด ์ค‘๋ณต ๊ฐ’ ๊ตฌํ•˜๊ธฐ

by 1mj 2022. 6. 23.

๋ฐฐ์—ด ๋‚ด์—์„œ ์ค‘๋ณต ๊ฐ’์„ ์ถ”์ถœํ•˜๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด [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"]

๋Œ“๊ธ€