1

I am using react-admin SelectInput and uses name as options but there are in the list that has the same name so the option shows duplicate values. I have tried doing research about filtering duplicate values but I can't seem to make it work.

My data looks like this:

data: [{name: "car1",id: 1,}, {name: "car1",id: 2,}, {name: "car2",id: 3,}]

Select options will display: car1, car 1, car 2 I want to display no duplicate: car1, car2

Here is my code:

<SelectInput optionText={<Choice/>}/>

const Choice = ({...record}) => {
    return(
        <span>{`${record && record.record.carName}`}</span>
    )
}

It allows me to play with the select options below like this and it display "test" so I think it can be done here but I cant find a good logic to implement the filter. Anyone has any idea? I'd greatly appreciate it!

 `${record && record.record.carName}` !== 'car1'  ?  <span>test</span> : null
1
  • 1
    I would suggest filtering out the data before passing it to <SelectInput />. Instead of filtering it within the choice itself. Commented Sep 7, 2021 at 2:48

2 Answers 2

1

You may filter with Set. Set stores only unique values. We filter the data based on whether the name already exists in the Set or not. I hope you don't care about the id. As the first item will remain and the last items will be removed as duplicates. Hope the idea is clear.

    let s = new Set();
    let newData =  data.filter(d => {
      if (!s.has(d.name)) {
        s.add(d.name);
        return d;
      }
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you guys! I only thought of doing it in the choices since I feel like it's a bit more complicated to implement filter in the data with react-admin but I'll try and see if I can make it work
1

If all you want is that there are no duplicates in the selection, I would suggest that you filter them before sending them to SelectInput.

You can do this by the following:

const data = [{name: "car1",id: 1,}, {name: "car1",id: 2,}, {name: "car2",id: 3,}];

const uniqueChoices = data.reduce((acc, choice) => {
  if (acc.some(item => item.name === choice.name) {
    return acc;
  }
  return [...acc, item]
}, []);

<SelectInput choices={uniqueChoices} />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.