하나의 Object Array에서 중복값 제거하기 (Remove duplicates from one Object Array)

업무를 하다가 Object Array에서 중복값을 제거할 필요가 생겼다.

예전에는 이렇게 하나하나 찾아서 해결했던 것들을 자세히 기록하지 않았는데, 그래도 기록을 해놓는 것이 나도 기억해내기 좋고 (같은 문제를 겪을 수 있으니까) 다른 사람에게도 도움이 될 것 같아서 적어보았다.

처음에는 filter 를 적용해야했다. 그래서 쉽게 풀릴줄 알았는데 동일한 값을 중복해서 저장하고 있었다. 그냥 들어오는대로 무조건 저장하는 로직. 그래서 똑같은 값에 대한 중복도 제거해줘야했다.

이 문제 때문에 찾은게 reduce인데 음 내가 적용해봤던 방법은 Object Array 자체에 대해서 중복 제거는 안 되고 Object 말고 Value Array에 대해서 중복 제거가 가능했다. 그러려면 map을 써야겠다고 생각했다.

filter는 value만 return 하지 않고 Object 통째로 return한다.

map은 value만 리턴 가능한데 if문을 conditional하게 적용하면 그 조건에 맞지 않는 것에 대해서 undefined가 떴다. 이 undefined는 제거가 안 된다고 한다.

그래서 1차 filter 2차 map 3차 reduce를 적용해서 제거하게 되었다… 아마 더 간결한 코드가 있을 것 같은데 우선 여기까지 idea develop한 것을 정리한다.

array = [{“entity”:”color”,”value”:”red”},{“entity”:”color”,”value”:”yellow”},{“entity”:”color”,”value”:”pink”},{“entity”:”color”,”value”:”blue”},{“entity”:”color”,”value”:”red”},{“entity”:”furniture”,”value”:”chair”}]

위와 같은 array에 아래 코드를 적용하면 중복값이 제거된 value array가 남는다.

array.filter(e=> e.value != ‘yellow’ && e.entity ===’color’).map(e=> e.value).reduce(function(a,b){if (a.indexOf(b) <0) a.push(b); return a;},[])

 

스크린샷 2019-03-05 오전 8.00.22

스크린샷을 보면 처음에 array가 있었고, array.filter(e=> e.value != ‘yellow’ && e.entity ===’color’) 코드를 적용해서 entity는 color이면서 value는 yellow가 아닌 object로 구성되어있는 array가 필터화되어서 남는다.

array.filter(e=> e.value != ‘yellow’ && e.entity ===’color’).map(e=> e.value) 여기에 map을 이용해서 value array만 남기고 거기에서 중복값을 제거하는 코드를 추가하면 array.filter(e=> e.value != ‘yellow’ && e.entity ===’color’).map(e=> e.value).reduce(function(a,b){if (a.indexOf(b) <0) a.push(b); return a;},[]) 완성된다.

처음으로 코드 작성한 것을 워드프레스에 올려 보았는데 code snippet을 보기 좋게 색깔을 바꾸는 등 올릴 수 있는 방법을 찾아봐야겠다.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s