• for문 + indexOf()

중복값의 인덱스 번호를 duplication 배열에 담는다.

const arr = ['a', 'b', 'c', 'c', 'd', 'e', 'a', 'a']
const duplication = []

for(let i = 0; i < arr.length; i++) {
    if(arr.indexOf(arr[i]) !== i) {
        duplication.push(i)
    }
}

duplication // [3, 6, 7]
  • filter() + indexOf()

filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소들을 모아 새로운 배열로 반환한다.

indexOf() 메서드는 호출한 string 객체에서 주어진 값과 일치하는 첫번째 인덱스를 반환한다.

const arr = ['a', 'b', 'c', 'c', 'd', 'e', 'a']
arr.filter((item, index) => arr.indexOf(item) !== index) // ['c', 'a']

 

  • 전개연산자 + new Set()

전개 연산자를 사용하면 배열이나 문자열 같이 반복 가능한 0개 이상의 인수 또는 요소를 확장하여, 0개 이상의 키-값 쌍으로 객체를 확장시킬 수 있다.

Set 객체는 자료형에 관계 없이 원시값(string, number, bollean, undefined, null 등..)과 객체 참조 모두 유일한 값을 저장할 수 있다.

= 중복된 값이 있으면 1개만 남긴다. (중복 혀용 X)

const arr = ['a', 'b', 'c', 'c', 'd', 'e']
[...new Set(arr)] // ['a', 'b', 'c', 'd', 'e']

 

  • Array.from() + new Set()

Array.from() 메서드는 유사 배열 객체나 반복 가능한 객체를 얕게 복사해 새로운 배열을 만든다.

const arr = ['a', 'b', 'c', 'c', 'd', 'e']
Array.from(new Set(arr)) // ['a', 'b', 'c', 'd', 'e']

 

  • filter() + indexOf()

filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소들을 모아 새로운 배열로 반환한다.

indexOf() 메서드는 호출한 string 객체에서 주어진 값과 일치하는 첫번째 인덱스를 반환한다.

const arr = ['a', 'b', 'c', 'c', 'd', 'e']
arr.filter((item, index) => arr.indexOf(item) === index) // ['a', 'b', 'c', 'd', 'e']

+ Recent posts