Skip to content

Instantly share code, notes, and snippets.

@dammyammy
Last active December 15, 2021 23:43
Show Gist options
  • Save dammyammy/87e6c37d2e19f357b0643cb75d392e0c to your computer and use it in GitHub Desktop.
Save dammyammy/87e6c37d2e19f357b0643cb75d392e0c to your computer and use it in GitHub Desktop.
Fix That moves the arrays by value
const blocks = [
{
"id":"GZ9oeIry1l",
"type":"outlineTopic",
"data":{
"text":"Section 1",
"level":4,
"metadata":{
"id":"f39bfcf5-98e6-47da-a214-84d8d1ac27c7"
}
}
},
{
"data":{
"metadata":{
"id":"cfe9307a-152e-456b-9db2-a6ce256e6415"
},
"sentences":[
{
"rewrites":[
"Sentence 1"
],
"selected":0
}
]
},
"type":"paragraph"
},
{
"id":"4Pr7MC_D0a",
"type":"outlineTopic",
"data":{
"text":"Section 2",
"level":4,
"metadata":{
"id":"6834558e-66cf-4684-8fed-94f86875e423"
}
}
},
{
"data":{
"metadata":{
"id":"9191cc8d-ce45-4398-b687-733a1fe9121e"
},
"sentences":[
{
"rewrites":[
"Sentence 2"
],
"selected":0
}
]
},
"type":"paragraph"
}
];
function findIndexesByIds(blocks, ids) {
var indexes = [];
for (var i = 0; i < blocks.length; i++) {
if (ids.includes(blocks[i].data.metadata.id)) {
indexes.push(i);
}
}
return indexes;
}
function moveBlocksByIndexesTo(blocks, indexes, toIndex) {
var newBlocks = [];
for (var i = 0; i < blocks.length; i++) {
if (!indexes.includes(i)) {
newBlocks.push(blocks[i]);
}
}
for (var i = 0; i < indexes.length; i++) {
newBlocks.splice(toIndex + i, 0, blocks[indexes[i]]);
}
return newBlocks;
}
const indexes = findIndexesByIds(blocks, [
//"f39bfcf5-98e6-47da-a214-84d8d1ac27c7",
//"cfe9307a-152e-456b-9db2-a6ce256e6415",
"6834558e-66cf-4684-8fed-94f86875e423",
"9191cc8d-ce45-4398-b687-733a1fe9121e"
])
console.log(moveBlocksByIdTo(blocks, indexes, 0))
@dammyammy
Copy link
Author

I believe the function is self-explanatory, you simply need to pass in the blocks alongside an array of the ids to be moved when dragged, we were able to get that done already yesterday. So I decided to work up from that state. The final argument for the function is the toIndex which react-beautiful-dnd already provides. This should help us move a single block or multiple blocks as tested.

As for what the code does, we first loop through to identify the indexes of the passed ids (perhaps there is a more efficient way to do this, but this works), next with the indexes we go-ahead to create a new block that does not include these indexes , then we add each index, individually to the toIndex plus its index in the indexes array

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment