0

I have created my drop down menu , but unfortunately it recieves an duplicated value from the API . I receive certain amount of documents from the BE and some of the are have the same name so in my dropdown i receive a duplication of the names . My code looks like this :

My function

divideItems = () => {

        let startIndex = ((parseInt(this.state.activePaginationTab) + 1) * this.state.rowsPerPage) - this.state.rowsPerPage;
        let endIndex = (parseInt(this.state.activePaginationTab) + 1) * this.state.rowsPerPage - 1;
        let tabItems = [];

        for (let i = startIndex; i <= endIndex; i++) {
            if (this.state.items[i]) {
                tabItems.push(this.state.items[i]);
            }
        }

        this.setState({
            tabItems: tabItems
        }, () => {

        });

My Rendering

<RBS.Dropdown>
     <RBS.Dropdown.Toggle  id="dropdown-invoice-header">
          {translations.type}
     </RBS.Dropdown.Toggle>

         <RBS.Dropdown.Menu>
              {this.state.tabItems.map(item => (
       <RBS.Dropdown.Item >{item.documentType}</RBS.Dropdown.Item>
))}
           </RBS.Dropdown.Menu>
      </RBS.Dropdown>

The result duplicating items in my dropdown menu .

enter image description here

2
  • do you have duplicated entries in state.tabItems as well? Aug 6, 2019 at 12:50
  • Yes , because it is an table i use state.tabItems also a little bit further .
    – PandaMastr
    Aug 6, 2019 at 13:48

3 Answers 3

0

Remove the duplicates

const uniqueItems = [];
tabItems.map(item => {
    if (uniqueItems.indexOf(item.documentType) === -1) {
        uniqueItems.push(item.documentType)
    }
});


this.setState({
    tabItems: uniqueItems 
}, () => {

1
  • there is no value after the arrow function item=>
    – PandaMastr
    Aug 6, 2019 at 13:49
0

You can use Set and the spread operator from ES6, because Set doesn't allow duplicates and will remove from array if found:

uniqueItems = [...new Set(tabItems)];

or shorter:

[new Set(tabItems)].map(item => { // do stuff });

or you can do .filter before and then .map:

uniqueItems = tabItems.filter((item, index) { return a.indexOf(index) == index; });

1
  • Yes , but i recieve back an empty array
    – PandaMastr
    Aug 6, 2019 at 13:50
0

You can filter out the duplicates before setting the state:

for (let i = startIndex; i <= endIndex; i++) {
    if (this.state.items[i] && tabItems.indexOf(this.state.items[i]) === -1) {
        tabItems.push(this.state.items[i]);
    }
}
1
  • @PandaMastr can you try console.log(tabItems); after the for-loop to see if it actually is being filtered
    – user10928257
    Aug 6, 2019 at 15:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.