• Home
  • About
    • lahuman photo

      lahuman

      열심히 사는 아저씨

    • Learn More
    • Facebook
    • LinkedIn
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

중복 객체 제거 하기

18 Jul 2021

Reading time ~1 minute

중복 제거 하기

단순한 숫자나 문자의 중복 제거는 Set을 이용하면 간단하게 처리 할 수 있습니다.

const list = ['1', '2', '3', '2', 1,2,3, 1,2,3];
// Set 을 이용한 방식
[...new Set(list)]
// filter를 이용한 방식
list.filter((item, index) => list.indexOf(item) === index);
// 결과
[ '1', '2', '3', 1, 2, 3 ]

하지만, 객체의 중복제거의 경우는 조금 다른 방식으로 처리 해야 합니다.

# 중복 제거가 안됨
const list = [{a:1, b:2}, {a:2, b:1}, {a:1, b:2}];

list.filter((item, index) => list.indexOf(item) === index);

// 결과 
[ { a: 1, b: 2 }, { a: 2, b: 1 }, { a: 1, b: 2 } ]

바로, JSON.stringify를 이용하는 방식입니다.

const list = [{a:1, b:2}, {a:2, b:1}, {a:1, b:2}];

const uniqueList = [...new Set(list.map(JSON.stringify))].map(JSON.parse);
// 결과 
[ { a: 1, b: 2 }, { a: 2, b: 1 } ]

다른 방식으로 key 값을 기준으로 unique 객체를 추출한다면 다음과 같은 방식으로도 가능합니다.

// a의 값이 key 인경우
const list = [{a:1, b:2}, {a:2, b:1}, {a:1, b:2}];

list.filter((item, index) => {
    const key = item.a;
    return index === list.findIndex((e)=> e.a === key);
});

위의 방식이 일반적으로 많이 쓰이는 방식 입니다.

참고 자료

  • [Javascript] array 중복 제거하는 방법(ES6)
  • The easy way to create a unique array of JSON Objects in JavaScript


javascriptunique Share Tweet +1