Home > DeveloperSection > Forums > How to remove duplicate entries in array?
David Miller

Total Post:30

Posted on    November-24-2014 10:07 PM

 JavaScript JQuery  Array 

 1 Reply(s)
 517  View(s)
Rate this:

I have an array of data returned from my server. From this array I need to get an array of Topics and an array of SubTopics:

var data =


{"topicId":1,"subTopicId":1,"topicName":"J","subTopicName":" Ar"},

{"topicId":1,"subTopicId":2,"topicName":"J","subTopicName":" Us"},

{"topicId":1,"subTopicId":3,"topicName":"J","subTopicName":" Ut"},

{"topicId":2,"subTopicId":4,"topicName":"L","subTopicName":" Ov"},

{"topicId":2,"subTopicId":5,"topicName":"L","subTopicName":" El"},

{"topicId":2,"subTopicId":6,"topicName":"L","subTopicName":" In"},

{"topicId":2,"subTopicId":7,"topicName":"L","subTopicName":" Pr"},

{"topicId":2,"subTopicId":8,"topicName":"L","subTopicName":" Va"},

{"topicId":2,"subTopicId":9,"topicName":"L","subTopicName":" Pa"}


I have code that I use to reformat this data and just give me topic information:

var topics = data.map(function (t) {

                    return {

                        id: t.topicId, name: t.topicName



But this gives me three entries for topicId 1 and six entries for topidId 2.

How I can filter out duplicate entries so I can for example the above would just give me a topic array of two entries. One for each topicId

Please no jQuery, lodash or other framework solutions as I didn't include these in the tags. thanks

Kamlakar Singh
Kamlakar Singh

Total Post:194

Posted on    November-25-2014 2:11 AM

This should work

topics = data.filter(function(item, index, data) {

   for (var i = 0; i < data.length; i++) {

      if (item.topicId === data[i].topicId) break;


   return index === i;

}).map(function (item) {

    return {

        id: item.topicId,

        name: item.topicName



If duplicate entries are equal, you can simplify filter function

data.filter(function(item, index, data) {  

   return data.indexOf(item) === index;



Don't want to miss updates? Please click the below button!

Follow MindStick