HOW TO REMOVE DUPLICATE ENTRIES IN ARRAY?

David Miller

Total Post:30

Points:210
Posted by  David Miller
 792  View(s)
Ratings:
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

  1. Kamlakar Singh

    Post:194

    Points:1396
    Re: How to remove duplicate entries in array?

    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;

    })

     

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!