[JS] 배열 중복 제거

Benza·2022년 1월 9일
0

🔎

목록 보기
1/11

배열에서 중복 제거하기

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에 넣게 되면, 중복되는 값이 사라집니다.

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

이 방법을 이해하기 위해서는 filtrer와 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']
  1. 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 이다
profile
Understanding the impression

0개의 댓글