20241101 자바스크립트 배열 값 중복 체크

배열 값 중복 체크하기

Set 객체를 활용한다.
Set은 중복을 허용하지 않는 값을 모아놓은 Collection 객체다.
따라서 배열의 길이와 Set의 사이즈를 비교해보면 배열 값의 중복을 체크할 수 있다.

const myArr = [1, 2, 3, 4, 4];
const mySet = new Set(myArr);

if (myArr.length !== mySet.size) {
  console.log("중복");
}

//// 출력
// 중복

mySet

//// 출력
// Set(4) {1, 2, 3, 4}

Categories:

Updated:

Leave a comment