[Javascript] array 중복 제거하는 방법(ES6)

Dongmin Jang
5 min readFeb 21, 2019

--

아래글에 대한 번역 & 일부 내용 발췌한 글입니다.

const array = ['a' , 1, 2, 'a' , 'a', 3];
// 1: 'Set'
[...new Set(array)];// 2: 'Filter'array.filter((item, index) => array.indexOf(item) === index);// 3: 'Reduce'array.reduce((unique, item) => unique.includes(item) ? unique : [...unique, item], []);// RESULT:// ['a', 1, 2, 3]
  1. Set

Set 은 ES6 에서 등장한 새로운 data object 입니다. Set 은 unique 값만 저장할 수 있도록 하기 때문에 array에 넣게 되면, 중복되는 값이 사라집니다.

… spread operator 에 대해서는 다른 설명 하지 않겠습니다.

또한 array 에 Set 을 이용하는 것 대신에 Array.from 도 가능합니다.

const array = ['0', 1, 2, '0', '0', 3]
Array.from(new Set(array));
// ['0', 1, 2, 3]

2. Filter

이 방법을 이해하기 위해서는 fileter 와 indexOf 메소드를 이해해야 합니다.

indexOf 는 array 안에서 값을 제일 먼저 찾은 위치입니다.

filter는 array 내의 각 element 에 조건을 주어, true 값을 return 한 element 만 모아서 새로운 array 를 만드는 것입니다.

반대로 중복값만 가져올 수도 있습니다.

const array = ['0', 1, 2, '0', '0', 3]
array.filter(item, index) => array.indexOf(item) !== index);
// ['0', '0']

3. Reduce

reduce 메소드는 array 의 각 요소를 줄여주는데 사용됩니다. 그리고 그것들을 모아 최종 array 로 결합해주는데 이 때 전달 된 reduce 함수가 사용됩니다.

이 경우에, 넘겨준 reducer 함수는 최종 array에 값이 있는지 확인합니다. 포함 되어있지 않으면 최종 array 로 푸시하고, 아니면 건너 뛰고 return 합니다.

Reduce 는 항상 이해하기가 좀 난해한데, 아래 코드와 함께 결과를 확인해 봅시다.

const array = ['0', 1, 2, '0', '0', 3];
array.reduce((unique, item) => {
console.log(
// a. Item
item,
// b. Final Array (Accumulator)
unique,
// c. 조건(이 조건이 false여야만 값이 푸시된다
unique.includes(item),
// d. Reduce Function Result
unique.includes(item) ? unique : [...unique, item],
);
return unique.includes(item) ? unique : [...unique, item]
}, []); // 초기 Accumulator 는 빈 array 이다

item | Accumulator | push to accumulator | accumulator

‘0’___[]___________yes______[‘0’]

1___[‘0’]_________yes______[‘0’, 1]

2___[‘0’, 1]_______yes______[‘0’, 1, 2]

‘0’___[‘0’, 1]_______no______[‘0’, 1, 2]

‘0’___[‘0’, 1]_______no______[‘0’, 1, 2]

3___[‘0’, 1, 2]_____yes______[‘0’, 1, 2, 3]

추가로 다른 블로거가 퍼포먼스와 관련해서 내용을 정리한게 있어 수치만 가져와봤습니다.

출처: https://medium.com/r/?url=https%3A%2F%2Fblog.usejournal.com%2Fperformance-of-javascript-array-ops-2690aed47a50

위 실험 정보가 포스팅 된 이후에 다른 독자들의 의견에 따라 추가 실험을 진행해서 아래와 같은 결과가 업데이트 되었습니다. 이 실험은 test data에 따라 결과에 많은 영향을 미치는데 앞 전의 실험은 중복 데이터가 많았다고 합니다. 그래서 중복된 데이터가 없는 상황에서 테스트를 진행하여 아래와 같이 결과를 얻었다고 합니다. (Set 사용합시다..)

https://blog.usejournal.com/performance-of-javascript-array-ops-2690aed47a50

--

--