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

允我心安 提交于 2020-04-18 07:12:49

问题


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...!


回答1:


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 });
              }
            }); 


来源:https://stackoverflow.com/questions/58800392/reactjs-how-to-prevent-duplicate-values-in-array-push

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!