'data is getting diisplayed twice in list in react
I am getting data in the below format.
[
{
"country_id": 1,
"country_name": "INDIA",
"insurance_id": {
"insurance_id": 1,
"insurance_name": "LIC",
"createdAt": "2022-04-07T07:33:34.929Z",
"modifiedAt": "2022-04-07T07:33:34.929Z",
"deletedAt": null
}
},
{
"country_id": 2,
"country_name": "INDIA",
"insurance_id": {
"insurance_id": 101,
"insurance_name": "HDFC",
"createdAt": "2022-04-07T07:33:09.698Z",
"modifiedAt": "2022-04-07T07:33:09.698Z",
"deletedAt": null
}
},
{
"id": "7e71625d-cf8e-4793-ba15-2d84338fde13",
"createdAt": "2022-04-07T11:13:30.452Z",
"modifiedAt": "2022-04-07T11:13:30.452Z",
"deletedAt": null,
"country_id": 3,
"country_name": "PAKISTAN",
"insurance_id": null
}
}
]
I need to display country_name in the list. this value is duplicate in above data so it is coming twice. I need to display only one time in list.
below is my code.
const [countryName, setCountryName]=useState([]);
const fetchCountry = async ()=>{
const {data}= await httpClient.get( config.resourceServerUrl+"/country");
data.length>0? setCountryName(data): setCountryName([]);
}
I am using react-select component to display list.
<Select
id="country"
name="contry"
placeholder="Select the Country"
className="align-items-center justify-content-center"
options={countryName.map((country:Country)=>
({ label: country.country_name, value: country.id })
)}
onChange={selectInsurer}
/>
how can I make this list unique?
Solution 1:[1]
You can preprocess your list before giving it to the Select component, like this:
const uniqueCountries = [];
for(let country of countryName){
if(!uniqueCountries.find(c => c.country_name === country.country_name)){
uniqueCountries.push(country);
}
}
Solution 2:[2]
You can create a list with all the values from your file, even the duplicate ones, then you can refer to this this question and the accepted answer, it shows you how to create a unique list from a list with duplicates.
Solution 3:[3]
I would create a new list containing only distinct country names, like this:
const countries = new Set()
obj.forEach(country => countries.add(country.country_name))
const list = Array.from(countries) // pass this array as options prop
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 | B. Ma |
| Solution 2 | robinood |
| Solution 3 | BiciAP |

