Search code examples
javascriptarraysreactjsecmascript-6array-push

ReactJS: How to prevent duplicate values in array.push?


While selecting one option in the Select box at that time rest of the options are become multiple values. How can i prevent this duplicate values ?

import Select from 'react-select';
const dataOptions = []; 
class App extends React.Component {
    constructor(props) {
        super(props);
        this.data = [];
        this.getData();
    }
    getData = () => { api.request({url: `/getdata`}).then(res => res.map(el => this.data[el.id] = el.name)) }

    addData = () => {
        const { selectedId } = this.state;
        var datas = this.data;
        console.log(datas);
        datas.map((name, index) => {
            if (!dataOptions.includes(name)) {
                console.log('b4 push:', dataOptions)
                dataOptions.push({ value: index, label: name });
                console.log('aftr push:', dataOptions)
            }
        });
        return (
            <Select options={dataOptions}
            isMulti
            />
        );
    }
}

Something is wrong happening in this syntax:

datas.map((name, index) => {
  if (!dataOptions.includes(name)) {
       dataOptions.push({ value: index, label: name });
  }
}); 

Console Results

[ "data-1", "data-2", "data-3"]

b4 push: [
  {value: 1, label: "data-1"}
  {value: 2, label: "data-2"}
  {value: 3, label: "data-3"}
]

aftr push: [
  {value: 1, label: "data-1"}
  {value: 2, label: "data-2"}
  {value: 3, label: "data-3"}
]

P.S: Here in aftr push i have already selected first option from drop down; so in result if should not be displayed in the array values.

Thanks in advance...!


Solution

  • The destructuring syntax should be like below

    datas.map(({name, index}) => {
          if (!dataOptions.includes(name)) {
               dataOptions.push({ value: index, label: name });
          }
        }); 
    

    Moreover you don't need external array to push the data inside map function as the function by default returns an array, you can do simply like below

     let expected_data=datas.map(({name, index}) => {
                  if (!dataOptions.includes(name)) {
                     return  { value: index, label: name };// return a value
                  }
                }); 
    

    The expected_data will contain the data you need after operation

    See the snippet-

    let data = [{
      "name": 1,
      "index": 2
    }, {
      "name": 11,
      "index": 21
    }]
    
    console.log(data.map(({
      index,
      name
    }) => {
    
      return {
        value: index,
        label: name
      }
    
    }))

    You better use Array.some() for what you are looking

     datas.map((name,index) => { // here index is the iterator
                    if(!dataOptions.some(({value,label})=>label==name  ))
                {
                       dataOptions.push({ value: index, label: name });
                  }
                });