Melina Melina - 1 year ago 119
Javascript Question

How can I map an array with duplicate values to a unique array in Javascript?

I have the following array:

var tst =

Is there an easy way that I can map that to this kind of array where topicId > id and topicName > name:

var t =

I am using a modern browser and I also have _lodash if that helps. Note that there will be about 100 rows in the tst array so I don't need a very optimized solution. A simple and easy to maintain solution would be more important.

Answer Source


_.uniqBy is now preferable

Full working example here

var tst = [

var result =, 'topicId'), function (item) {
    return {
        id: item.topicId,
        name: item.topicName


LEGACY is a good start

_.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');

Your code would look like this to get topics unique by id

var t = _.uniq(tst, 'topicId');


I made a jsfiddle


Removed unnecessary uniqueness of names

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download