Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse an array with React hooks

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.

like image 797
peter flanagan Avatar asked Mar 05 '23 14:03

peter flanagan


2 Answers

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

like image 198
Shubham Khatri Avatar answered Mar 16 '23 21:03

Shubham Khatri


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);
like image 31
Kamil Kiełczewski Avatar answered Mar 16 '23 19:03

Kamil Kiełczewski