Home > Software design >  Next Js Loop through object to map and remove duplicates for dropdown value for each select
Next Js Loop through object to map and remove duplicates for dropdown value for each select

Time:07-11

I am trying to generate dropdown values from the below JSON but am unable to remove duplicate values from each dropdown.

  const [items] = useState([
  {
      "Id": 502,
      "CityId": 2,
      "CityName": "Ex. Mumbai",
      "DepartureId": 3762,
      "DeptDate": "22 Jul 2022 "
    },
    {
      "Id": 502,
      "CityId": 2,
      "CityName": "Ex. Mumbai",
      "DepartureId": 3763,
      "DeptDate": "05 Aug 2022 "
    },
    {
      "Id": 502,
      "CityId": 1,
      "CityName": "Ex. Ahmedabad",
      "DepartureId": 3762,
      "DeptDate": "22 Jul 2022 "
    },
    {
      "Id": 502,
      "CityId": 7,
      "CityName": "Ex. Delhi",
      "DepartureId": 3762,
      "DeptDate": "22 Jul 2022 "
    },
    {
      "Id": 502,
      "CityId": 9,
      "CityName": "Ex. Bangalore",
      "DepartureId": 3762,
      "DeptDate": "22 Jul 2022 "
    },
    {
      "Id": 502,
      "CityId": 9,
      "CityName": "Ex. Bangalore",
      "DepartureId": 3763,
      "DeptDate": "05 Aug 2022 "
    },
]);

My Dropdowns:

CityName DeptDate

using

<select>
            {items.map(item => (
                <option  key={item.CityId} value={item.CityId}>
                    {item.CityName}
                </option>
            ))}
</select>

Also, I tried using

{Array.from(new Set(items.map(obj => obj.CityName))).map(cn => {
                return <option value={cn.CityName}>{cn}</option>
            })}

but don't know how to add "cn.CityId" as an option value when looping using only "obj.CityName".

How can I fix this? Thank you for support in Advance !!

CodePudding user response:

You can remove duplicate element in array by simple function

const cityNames = items.map(i => i.CityName);
const deptDates = items.map(i => i.DeptDate);
const filtereName = items.filter(({ CityName }, index) => !cityNames.includes(CityName , index   1))
const filtereDate = items.filter(({ DeptDate}, index) => !deptDates.includes(DeptDate, index   1))

<select>
    {filtereName.map(item => (
        <option  key={item.CityId} value={item.CityId}>
            {item.CityName}
        </option>
    ))}
</select>
  • Related