How to map an array with duplicate values to a unique array in JavaScript?

Sometimes, we want to map an array with duplicate values to a unique array in JavaScript.

In this article, we’ll look at how to map an array with duplicate values to a unique array in JavaScript.

How to map an array with duplicate values to a unique array in JavaScript?

To map an array with duplicate values to a unique array in JavaScript, we can use some array methods.

For instance, we write:

const data = [{
    "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"
  }
];

const noDups = [...new Set(data.map(d => d.topicId))].map(topicId => {
  return data.find(d => d.topicId === topicId)
})
console.log(noDups)

We create a new set with the topicIds with the duplicates removed and spread that back to an array.

Then we call map with a callback to return the first item with the given topicId in data.

Therefore, noDups is:

[
  {
    "topicId": 1,
    "subTopicId": 1,
    "topicName": "a",
    "subTopicName1": "w"
  },
  {
    "topicId": 2,
    "subTopicId": 2,
    "topicName": "b",
    "subTopicName2": "x"
  },
  {
    "topicId": 3,
    "subTopicId": 3,
    "topicName": "c",
    "subTopicName3": "y"
  }
]

Conclusion

To map an array with duplicate values to a unique array in JavaScript, we can use some array methods.