Created
April 24, 2020 06:16
-
-
Save jericbas/edfff58892d6aa03033ca560168aac69 to your computer and use it in GitHub Desktop.
Move element of array of object to another position/index
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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