Melina Melina - 1 month ago 13
Javascript Question

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

I have the following array:

var tst =
[
{"topicId":1,"subTopicId":1,"topicName":"a","subTopicName":"w"},
{"topicId":1,"subTopicId":2,"topicName":"b","subTopicName":"x"},
{"topicId":1,"subTopicId":3,"topicName":"c","subTopicName":"y"},
{"topicId":2,"subTopicId":4,"topicName":"c","subTopicName":"z"}
]


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

var t =
[
{"id":1,"name":"a"},
{"id":2,"name":"c"}
]


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

MOST RECENT

_.uniqBy is now preferable

Full working example here

var tst = [
 {"topicId":1,"subTopicId":1,"topicName":"a","subTopicName1":"w"},
 {"topicId":2,"subTopicId":2,"topicName":"b","subTopicName2":"x"},
 {"topicId":3,"subTopicId":3,"topicName":"c","subTopicName3":"y"},
 {"topicId":1,"subTopicId":4,"topicName":"c","subTopicName4":"z"}
];

var result = _.map(_.uniqBy(tst, 'topicId'), function (item) {
    return {
        id: item.topicId,
        name: item.topicName
    };  
});

console.log(result);

LEGACY

http://lodash.com/docs#uniq 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');

EDIT

I made a jsfiddle

http://jsfiddle.net/q5HNw/

UPDATE

Removed unnecessary uniqueness of names

http://jsfiddle.net/q5HNw/1/

Comments