Given an index, swap array elements accordingly
Solution 1:
Just identify the previous 0 with findIndex
, assign 1 to it, and assign 0 to the idx
?
function rearrange(array: number[], idx: number) {
const arr = [...array];
arr[arr.indexOf(0)] = 1;
arr[idx] = 0;
return arr;
}
Another approach...
const rearrange = (array: number[], idx: number) => (
array.map((_, i) => i === idx ? 0 : 1)
);