2

I'm trying to remove existing specific value in an array before adding or push another updated value. My purpose is to avoid duplicate same id and value to array. What i'm trying to achieve is when onchange triggered check if that value is existing on array and if exist remove the old one and push the update value.

  const [array, setnewarray] = useState([]);
     function handlechangeselected(val,id){

       var newarray = array;
       const valueToRemove = id;
       newarray.filter(item => item.id === valueToRemove);

        newarray.push({ value: val, id:id });
       setnewarray(newarray);

  }




  <select                                                                              
   onChange={(e) => handlechangeselected(e.target.value,row.ID)}                                                                                
  >

      <option value="0">0</option>                                                                             
      <option value="1">1</option>                                                                           
      <option value="2">2</option>

  </select>

1 Answer 1

1

The first issue is that filter doesn't modify the array, but rather returns a new array. You're not using the returned array, so newArray is unchanged.

The other issue is that filter filters out out any values that return false from your callback, so you want your filter to return true for any items that don't match valueToRemove (in other words, !== instead of ===). You can also use .concat to chain after array.filter.

Here it is, simplified a bit:

     const [array, setNewArray] = useState([]);

     function handlechangeselected(value, id){
       const newArray = array
         .filter(item => item.id !== id)
         .concat({ value, id });

       setNewArray(newArray);
     }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.