Skip to content

Instantly share code, notes, and snippets.

@Woodsphreaker
Created June 5, 2017 14:47
Show Gist options
  • Save Woodsphreaker/abf49f2be69354f4ca0654f233281f3e to your computer and use it in GitHub Desktop.
Save Woodsphreaker/abf49f2be69354f4ca0654f233281f3e to your computer and use it in GitHub Desktop.
Change position of element in array without loop
const arr = [1,2,3,4,5,6,7,8,9]
const fnMove = (list) => (ele, newPos) => {
const _arr = [].concat(list)
const arrPos = Array.from({length:2})
arrPos[0] = _arr.indexOf(ele)
arrPos[1] = _arr[newPos]
_arr[newPos] = ele
_arr[arrPos[0]] = arrPos[1]
return _arr
}
// Find and get position of element 5 and put in position 8
console.log(fnMove(arr)(5,8)) // [1,2,3,4,5,6,7,8,9]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment