Skip to content

Instantly share code, notes, and snippets.

@SebastianUdden
Last active May 16, 2022 12:40
Show Gist options
  • Select an option

  • Save SebastianUdden/8c9d270611530bf8420c9894c86f3e52 to your computer and use it in GitHub Desktop.

Select an option

Save SebastianUdden/8c9d270611530bf8420c9894c86f3e52 to your computer and use it in GitHub Desktop.
Swap element positions in an array
const handleChangePosition = (
oldIndex,
newIndex,
array
) => {
if (newIndex < 0 || newIndex > array.length - 1) return [];
const newArray = [...array];
const oldObj = array[oldIndex];
const newObj = array[newIndex];
newArray[oldIndex] = newObj;
newArray[newIndex] = oldObj;
return newArray;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment