Using javascript is there any quick way to swap 2 items in an array?
So if it was a boolean you could do
const [isTrue, setIsTrue] = useState(false);
setIsTrue(!isTrue);
but say I have an array
// I want to swap the items in the array on a click
const [trueOrFalse, setTrueOrFalse] = useState([true, false]);
and I want to switch these, is there a quick way of swapping the items in the array if there are two items
setTrueOrFalse(!trueOrFalse); // would equal [false, true]
<div onClick={() => setTrueOrFalse()} />Swap items in array</div>
I am trying to take the element at index 0 and move it to index 1, and vice versa.
You can simply use de-structuring with useState setter callback method
// I want to swap the items in the array on a click
const [trueOrFalse, setTrueOrFalse] = useState([true, false]);
const swapState = () => {
setTrueOrFalse(prevState => {
const [val1, val2] = prevState;
return [val2, val1];
})
}
<div onClick={() => swapState()} />Swap items in array</div>
Working demo
Try
let a=[true, false];
// inverse values
let b= a.map(x=>!x)
// swap sequence (inplace)
a.reverse();
console.log('inverse values', b);
console.log('swap sequence', a);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With