#ForEach() unique values (React.js)

2 messages · Page 1 of 1 (latest)

scenic sorrel
#

Im using react and have an array of objects. I have created a <select> and want to add the names from the arrays as an <option> but each name is in more than 1 element, and I want them to only be added once as an <option>

<select id='sel' value={picked} onChange={x=>setPicked(x.target.value)}>
    <option disabled selected>Select a student</option>
</select>
   function addsss(){
        if(x=>!sel.includes(x.studentName))
        {
               allStudentData.forEach(x=>{
               sel.innerHTML += '<option value="' + x.studentName+ '">' + x.studentName + "<option/>"    
           })  ;
   }
}```
This adds the more than once 
(I have tried other things that didnt work either so im asking for help)
scenic sorrel
#

I found a way to do it but its not perfect yet. I will share it for anyone who may be interested.

  1. I made a new array with only the unique studentNames like this
const unique = [...new Set(allStudentData.map(
item => item.studentName)
)];```
Then I added them into the <select> with this.
 ```javascript
function addsss(){
unique.forEach(x=>{sel.innerHTML += 
'<option value="' + x + '">' + x + "<option/>"    
    });
}```