-1

there is a sample data:

[
  {
    id: 1,
    stockCount: 12,
    category: "car",
  },
  {
    id: 2,
    stockCount: 12,
    category: "car",
  },
  {
    id: 3,
    stockCount: 12,
    category: "car",
  },
  {
    id: 4,
    stockCount: 12,
    category: "plane",
  },

  {
    id: 5,
    stockCount: 12,
    category: "plane",
  },
  {
    id: 6,
    stockCount: 12,
    category: "plane",
  },
  {
    id: 7,
    stockCount: 12,
    category: "plane",
  },
  {
    id: 8,
    stockCount: 12,
    category: "ship",
  },
  {
    id: 9,
    stockCount: 12,
    category: "ship",
  },
  {
    id: 10,
    stockCount: 12,
    category: "ship",
  },
  {
    id: 11,
    stockCount: 12,
    category: "ship",
  },
];

what I want is to get the categories here. when I do this with the .map() function it returns all the categories one by one. but what I want is just to get it in "car", "plane", "ship" format. I don't want copies. how do i know this?

here my loop code :

{DummyProducts.map((item, index) => (
        <Link to="/" className={Style.NavBottomLink}>
          {item.category}
        </Link>
      ))}
Hashim Hashimli
  • 113
  • 3
  • 14

2 Answers2

1

You can readily do this with a Set, which ignores duplicates if you try to add them:

const categorySet = new Set();
for (const {category} of DummyProducts) {
    categorySet.add(category);
}

or somewhat more concisely:

const categorySet = new Set(DummyProducts.map(({category}) => category));

If you want that as an array (for map), you can use [...categorySet]. So for instance, having done the above:

{[...categorySet].map(category => (
    <Link to="/" className={Style.NavBottomLink}>
        {category}
    </Link>
))}

Or if you want to convert to array immediately:

const categorySet = new Set();
for (const {category} of DummyProducts) {
    categorySet.add(category);
}
const categories = [...categorySet];

or:

const categories = [...new Set(DummyProducts.map(({category}) => category))];

Then use it directly:

{categories.map(category => (
    <Link to="/" className={Style.NavBottomLink}>
        {category}
    </Link>
))}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

You can do it using a Set as follows:

const unique_categories = [...new Set(DummyProducts.map(item => item.category))];
(
    unique_categories.map(category => (
        <Link to="/" className={Style.NavBottomLink}>
              {category}
        </Link>
    )
)
Numan Ijaz
  • 878
  • 1
  • 8
  • 18