1
const array = [{
        productname: "productname1",
        category: "category1"
    },
    {
        productname: "productname2",
        category: "category2"
    },
    {
        productname: "productname3",
        category: "category3"
    },
    {
        productname: "productname4",
        category: "category1"
    },
    {
        productname: "productname5",
        category: "category2"
    }
]

I want to get an output where I can get all the categories without having duplicates

I tried using map and filter but my output was:

["category1" "category2", "category3","category1","category2"]

my desired output is

["category1" "category2", "category3"]

How can I achieve this?

  • 1
    Both what you've described as the output you got, and the output you want, are invalid JavaScript syntax. Did you want an array? Also, **show** us the code you've already tried, since you say you have tried to do this. That way, we can help you understand what is wrong with it. – T.J. Crowder Aug 31 '21 at 14:51
  • the curly bracket was a mistake , the output is an array – Thankgod Okpara Aug 31 '21 at 14:58
  • 1
    Please use the "edit" link to fix errors in the question. – T.J. Crowder Aug 31 '21 at 15:01

1 Answers1

4

You can use map to extract the category property values and Set with spread syntax to get the unique:

const array = [{
    productname: "productname1",
    category: "category1"
  },
  {
    productname: "productname2",
    category: "category2"
  },
  {
    productname: "productname3",
    category: "category3"
  },
  {
    productname: "productname4",
    category: "category1"
  },
  {
    productname: "productname5",
    category: "category2"
  }
]

const uniqueCategories = [...new Set(array.map(e => e.category))]
console.log(uniqueCategories)
Spectric
  • 30,714
  • 6
  • 20
  • 43
  • I wonder how would Set compare to reduce or filter in terms of performance. – Robo Robok Aug 31 '21 at 14:53
  • 1
    @RoboRobok - (`reduce` is tangential, just another way to loop.) `filter` on what? You'd have to repeatedly search the target array to see if it had the elements, which is unlikely to be as efficient as building a `Set`. (But there's no need for the intermediate array above: `const set = new Set(); for (const {category} of array) { set.add(category); } const uniqueCategories = [...set];`) – T.J. Crowder Aug 31 '21 at 15:04
  • I know, I'm just thinking out loud. I don't know Set's performance. But I'd use Set in this case as well, of couse even if performance is different, it doesn't matter. Not sure what you mean by reduce() being tangential. I thought it was linear, just like map or filter. – Robo Robok Aug 31 '21 at 16:21