-
Notifications
You must be signed in to change notification settings - Fork 0
Description
javascript 배열 중복 제거 (ES6)
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]
- 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]
- 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']
- 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]
추가로 다른 블로거가 퍼포먼스와 관련해서 내용을 정리한게 있어 수치만 가져왔다.
