'How to exclude some options from React Select options

I have around 50 options to be shown in the react select options. But I want to exclude some of the options with logic to already posted values. The purpose is, that we have a form where we add values from the drop-down list. if one item is been added then that should not have to be shown in the dropdown list.

refactored code:

export default function App() {
  const choices = [
    {
      value: 0,
      label: "Container empty to shipper"
    },
    {
      value: 1,
      label: "Container pickup at shipper"
    },
    {
      value: 2,
      label: "Container arrival at first POL (Gate in)"
    },
    {
      value: 3,
      label: "Container loaded at first POL"
    }
  ];

  const postedList = [
    "Container empty to shipper",
    "Container pickup at shipper"
  ];
  return (
    <div className="App">
      <h1>Select Box</h1>
      <Select
        isClearable={false}
        // here the choices should be 2 eliminating the other 2 whose labels are matching to postedlist 
        options={choices}
        defaultValue={choices[0]}
        onChange={(choice) => console.log(choice.value)}
      />
    </div>
  );
}

Currently, it's rendering all 4 choices available but I want to return only 2 of them whose labels are not matching to postedlist

I also have created Codesandbox. If you want to see it there.



Solution 1:[1]

You can use Array.prototype.filter() and Array.prototype.includes() to filter out already posted items. Then use the filteredList as input to the Select component as below.

  const filteredList = choices.filter(({ label }) =>
    !postedList.includes(label)
  );

  return (
    <div className="App">
      <h1>Select Box</h1>
      <Select
        isClearable={false}
        options={filteredList}
        defaultValue={filteredList[0]}
        onChange={(choice) => console.log(choice.value)}
      />
    </div>
  );

Edit happy-wave-yktw2j

Solution 2:[2]

You can dynamically filter items and exclude them with the includes method.

    <Select
    options = {choices.filter((choice) => !postedList.includes(choice.label))}
    ...
    />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Yasin Br