Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing duplicate value from list of javascript objects in react js

I have react project and in that have a javascript array of object similar to given below and in that object it has a value called category.

const data = [{
    "id": 1,
    "item": "760",
    "price": "$609.05",
    "category": "BMW"
  }, {
    "id": 2,
    "item": "Frontier",
    "price": "$317.89",
    "category": "Nissan"
  }, {
    "id": 3,
    "item": "Odyssey",
    "price": "$603.64",
    "category": "BMW"
  }]

Im mapping through the list and displaying the category as shown below.

{data.map(item => (<span>{item.category}</span>))}

Here, the category duplicates and display several times when there are several similar items. Considering the given data list, the category BMW display twice.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What I want is, even if there are multiple similar categories, I only want to display once. Is this possible and how can I do it?

>Solution :

There can be various ways to reach the desired result. I would do it with a Set() and destructuring syntax:

{[...new Set(data.map(item => (<span>{item.category}</span>)))]}
const data = [{
  "id": 1,
  "item": "760",
  "price": "$609.05",
  "category": "BMW"
}, {
  "id": 2,
  "item": "Frontier",
  "price": "$317.89",
  "category": "Nissan"
}, {
  "id": 3,
  "item": "Odyssey",
  "price": "$603.64",
  "category": "BMW"
}]

const newData = [...new Set(data.map(item => ("<span>" + item.category + "</span>")))]

console.log(newData);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading