1

I have an array of data that I am using to create a drop down logic with.But there is a series of duplicate values when I create the drop-down using :

                    <select>
`                     `{
                        this.state.statistic_table.map((obj) => {
                            return <option value={obj.period}>{obj.period}</option>
                        })
                    }</select>

The long list of arrays contains a number of duplicate period values which are actually months. So in the dropdown I would get each and every value. I would like to eliminate the duplicates from the dropdown. How could I achieve that? Thanks

Derrick Omanwa
  • 457
  • 1
  • 5
  • 23
  • Please include the demo of your array data in your question – moshfiqrony May 09 '20 at 15:46
  • Does this answer your question? [Remove duplicates from an array of objects in JavaScript](https://stackoverflow.com/questions/2218999/remove-duplicates-from-an-array-of-objects-in-javascript) – wentjun May 09 '20 at 15:46

2 Answers2

3

One way to acheive that could be to use the Set API after mapping your array :

{Array.from(new Set(this.state.statistic_table.map(obj => obj.period))).map(period => {
    return <option value={period}>{period}</option>
})}

And then converting it back to an array using Array.from to map your component with it

Treycos
  • 7,373
  • 3
  • 24
  • 47
1

I will fix that on this way:

1) Using some events e.g. componentDidMount where you need to filter your array on next :

define an empty array in the state:

this.state = {
 let filteredArray = [];
}

On mount filter them :

componentDidMount() {
    let uniq = Array.from(new Set(this.state.statistic_table));
    this.setState(uniq);
}

If the object type is correct you can do something like this:

 <select>{
      this.state.filteredArray.map((obj) => {
           return <option value={obj.period}>{obj.period}</option>
      })
 }</select>
Milos N.
  • 4,416
  • 6
  • 18
  • 31