댓글 검색 목록

[javascript] JavaScript, 배열에서 중복을 찾는 방법

페이지 정보

작성자 운영자 작성일 20-11-18 13:26 조회 584 댓글 0

JavaScript 배열에서 중복을 찾고 제거하는 방법


중복을 제거하려는 경우 JavaScript에서 제공하는 Set 데이터 구조를 사용하는 매우 간단한 방법이 있습니다. 한 줄짜리입니다.


const yourArrayWithoutDuplicates = [...new Set(yourArray)]

중복 된 요소를 찾으려면 이 "중복 없는 배열"을 사용하고 원래 배열 내용에서 포함 된 각 항목을 제거 할 수 있습니다.


const yourArray = [1, 1, 2, 3, 4, 5, 5]

const yourArrayWithoutDuplicates = [...new Set(yourArray)]

let duplicates = [...yourArray]
yourArrayWithoutDuplicates.forEach((item) => {
  const i = duplicates.indexOf(item)
  duplicates = duplicates
    .slice(0, i)
    .concat(duplicates.slice(i + 1, duplicates.length))
})

console.log(duplicates) //[ 1, 5 ]


또 다른 해결책은 배열을 정렬 한 다음 "다음 항목"이 현재 항목과 동일한 지 확인하고 배열에 넣는 것입니다.


const yourArray = [1, 1, 2, 3, 4, 5, 5]

let duplicates = []

const tempArray = [...yourArray].sort()

for (let i = 0; i < tempArray.length; i++) {
  if (tempArray[i + 1] === tempArray[i]) {
    duplicates.push(tempArray[i])
  }
}

console.log(duplicates) //[ 1, 5 ]


이것은 객체가 아닌 원시 값에 대해서만 작동합니다. 개체의 경우 비교하는 방법이 필요합니다.



댓글목록 0

등록된 댓글이 없습니다.

웹학교 로고

온라인 코딩학교

코리아뉴스 2001 - , All right reserved.