Reputation: 189
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>
Upvotes: 2
Views: 5608
Reputation: 6529
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);
}
Upvotes: 1