[js] Set.prototype.size로 중복된 숫자 제거 알아보기

해나·2024년 2월 18일
post-thumbnail

Set objects are collections of values.
A value in the set may only occur once.

The size accessor property of Set instances returns the number of (unique) elements in this set.

const set1 = new Set();
const object1 = {};

set1.add(42);
set1.add('forty two');
set1.add('forty two');
set1.add(object1);

console.log(set1.size);
// Expected output: 3

set에 size를 호출하면 중복된 숫자 또는 문자열은 제외한 길이를 보여준다.

const mySet = new Set();
mySet.add(1);
mySet.add(5);
mySet.add("some text");

console.log(mySet.size); // 3

각기 다른 숫자, 문자열을 3개 넣으면 size는 3이 되고

const mySet = new Set();
mySet.add(1);
mySet.add(5);
mySet.add(5);

console.log(mySet.size); // 2

중복된 숫자 5를 두개 넣으면 size는 2가 된다.

이것을 통해
코딩 테스트 숫자 관련 문제에서 중복된 숫자를 제거한 길이는 무엇인지 알아낼 수 있다.

profile
hena.log("Markdown STH")

0개의 댓글