React中如何去除下拉框中的重复选项?
Got it, let's sort out that duplicate option problem in your dropdown! The root issue is that you're mapping over every entry in your statistic_table array directly—since multiple items share the same period value, you end up with repeated options. Here are two simple, effective solutions:
Method 1: Use a Set for Quick, Clean Deduplication
Sets automatically eliminate duplicate values, making this the most concise approach. We'll map the array to extract all period values, convert to a Set, then turn it back into an array:
render() { // Create an array of unique period values const uniquePeriods = [...new Set(this.state.statistic_table.map(item => item.period))]; return ( <select> {uniquePeriods.map(period => ( <option key={period} value={period}>{period}</option> ))} </select> ); }
This method is fast (O(n) time complexity) and works perfectly for simple values like month strings/numbers. Just note that in very old browsers, Sets might not preserve insertion order—but modern browsers handle this fine.
Method 2: Use reduce for Customizable Deduplication
If you need stricter control over the order or want to handle more complex deduplication logic later, use the reduce method to build an array of unique values manually:
render() { const uniquePeriods = this.state.statistic_table.reduce((uniqueArray, currentItem) => { // Only add the period if it's not already in the unique array if (!uniqueArray.includes(currentItem.period)) { uniqueArray.push(currentItem.period); } return uniqueArray; }, []); // Initialize with an empty array return ( <select> {uniquePeriods.map(period => ( <option key={period} value={period}>{period}</option> ))} </select> ); }
This has O(n²) time complexity, but for a list of months (max 12 unique values), that's totally negligible. It's great if you ever need to adjust the deduplication rule (e.g., comparing nested properties).
Important Note: Don't Forget the key Prop
I added the key prop to each <option>—React requires this for list items to optimize re-renders. Since we've deduplicated the periods, using period as the key is safe and unique.
内容的提问来源于stack exchange,提问作者Derrick Omanwa

