'How to only add unique values to a useState array and maintain maximum of length 3
So, I am trying to add max 3 values to a useState array and ensure all are unique and if fourth unique element is pushed it will replace the first element at index 0. ? Also, if the same element is clicked then it is removed from the array. However the function I wrote is not able to accomplish my objective.
const [chatbox,setChatBox]=useState([]);
chat=['a11','b11','c11','d11']
chat.map((c)=>(
<div
onClick={()=>addorRemoveitems(c)}
>
{c}
<div>
))
const addorRemoveitems=(cId)=>{
if (
chatbox.length <= 3 &&
chatbox.includes(cId)
) {
const newArray = chatbox.filter(
(c) => c !== cId
);
setChatBox(newArray);
} else if (
chatbox.length < 3 &&
chatbox.indexOf(cId) === -1
) {
setChatBox((prev) => [...prev, cId]);
} else if (
chatbox.length == 3 &&
chatbox.indexOf(cId) !== -1
) {
const newArray = chatbox.splice(
0,
1,
cId
);
setChatBox(newArray);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
