0

I have three dropdowns - Manufacturer, Province, and City - that fetch data from an API. The issue is that the dropdowns display duplicate values instead of showing each value only once.

Context:

  • The API contains data for around 50 products.
  • Some products share the same manufacturer, province, or city.

Objective:

  • Display unique values in each dropdown to enhance filtering capabilities.

Problem:

  • Current implementation populates dropdowns with repeated values, causing redundancy.

Example image of the issue: Visual of what's happening

My code:

export const Dropdown: React.FC<DropdownProps> = ({
  data,
  onChange,
  value,
  filterType,
}) => {
  const filteredData = data[0].equipments;

  // Filter the data based on the filterType
  const filteredOptions = filteredData.filter((i) => {
    if (filterType === "manufacturer") {
      return i.manufacturer;
    }
    if (filterType === "state") {
      return i.state;
    }
    if (filterType === "city") {
      return i.city;
    }

    return false;
  });

  return (
    <>
      <Select
        placeholder={getCustomPlaceholder(filterType)}
        value={value}
        onChange={onChange}
      >
        {filteredOptions.map((i) => (
          <option key={i.id} value={i[filterType]}>
            {i[filterType]}
          </option>
        ))}
      </Select>
    </>
  );
};

I'd appreciate any advice on how to get this working. Thank you!

jrad09
  • 39
  • 1
  • 5
  • Use the `set` operator to remove duplicates from the array https://www.javascripttutorial.net/array/javascript-remove-duplicates-from-array/ – Bennison J Jun 21 '23 at 13:48

1 Answers1

0

Based on this

  // Filter the data based on the filterType
  const filteredOptions = filteredData.filter((i) => {
    if (filterType === "manufacturer") {
      return i.manufacturer;
    }
    if (filterType === "state") {
      return i.state;
    }
    if (filterType === "city") {
      return i.city;
    }

    return false;
  }).filter((value, index, self) =>
    index === self.findIndex((t) => (
      t.filterType === value.filterType
    ))
  );
Gohchi
  • 434
  • 3
  • 12