Skip to content

Instantly share code, notes, and snippets.

@jericbas
Created April 24, 2020 06:16
Show Gist options
  • Save jericbas/edfff58892d6aa03033ca560168aac69 to your computer and use it in GitHub Desktop.
Save jericbas/edfff58892d6aa03033ca560168aac69 to your computer and use it in GitHub Desktop.
Move element of array of object to another position/index
const data = [
{id: 1, name: "Sample 1"},
{id: 2, name: "Sample 2"},
{id: 3, name: "Sample 3"}
]
const moveObject = (arr, targetKey, targetValue, newIndex) => {
const target = arr.find(value => value[targetKey] === targetValue)
const newArray = arr.filter(value => value[targetKey] != targetValue)
newArray.splice(newIndex, 0, target);
return newArray;
}
console.log(moveObject(data, 'id', 1, 2))
// [{"id":2,"name":"Sample 2"},{"id":3,"name":"Sample 3"},{"id":1,"name":"Sample 1"}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment