0

I am getting duplicate values from the select option in an edit form. For example, in the select option, I have A and B, and let say I have in the database recorded as B. So when I go into the edit form I should see B being selected which working fine so far. But I see A, B, B instead of A and B.

I am not sure how do I get rid of the duplicate values. Here is the code:

  <div className="col-sm-10">
           <select id="sourcename" className="form-control" name="source" onChange={handleChange}>
                 {sourceData.map(option => (
                      <option value={option._id}>{option.sourcename}</option>
                      ))}
                      <option selected value={data.source._id}>{data.source.sourcename}</option>
          </select>
       </div>

Many thanks in advance and greatly appreciate any helps. Thanks

Nat
  • 679
  • 1
  • 9
  • 24

2 Answers2

1

You can simply use the Set: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

const uniqueData = new Set(sourceData)
[...uniqueData].map(option => (
  <option value={option._id}>{option.sourcename}</option>
))}
Bart Krakowski
  • 1,655
  • 2
  • 8
  • 25
  • 1
    I'm afraid there is an error here. You cannot iterate `Set` with `map`, need to convert it to array with `Array.from(set)` – Michael Rovinsky Apr 27 '21 at 14:24
  • Thanks guys. The thing is the sourceData is already unique in value. I am guessing that the second option is the cause for the duplicate value: – Nat Apr 27 '21 at 14:30
  • So, I think the option outside the map is unnecessary. The options generated by the map should be sufficient. You can also remove this value from sourceData with the `slide` method: https://stackoverflow.com/questions/5767325/how-can-i-remove-a-specific-item-from-an-array – Bart Krakowski Apr 27 '21 at 14:36
0

This solved the issue for me

<option value={option.value} selected={optionsState == option.value}>{option.label}</option>
Nat
  • 679
  • 1
  • 9
  • 24