reorder items algorithm
-
20-08-2019 - |
Question
I've got an html table thus:
up | dn
[ ] Item 1
[x] Item 2
[ ] Item 3
[ ] Item 4
[x] Item 5
[ ] Item 6
[ ] Item 7
If 2 & 5 are checked and I click up, the result is:
up | dn
[x] Item 2
[x] Item 5
[ ] Item 1
[ ] Item 3
[ ] Item 4
[ ] Item 6
[ ] Item 7
If I click dn, the result is:
up | dn
[ ] Item 1
[ ] Item 3
[ ] Item 4
[ ] Item 6
[x] Item 2
[x] Item 5
[ ] Item 7
In other words, the items are grouped in the chosen direction, and then moved one row in that direction. Anyone have a good algorithm for this? I'm sure I can write something without much difficulty, but it seems like the kind of thing that should be "out there"....
Solution
I think I'm leaning toward a cut-and-paste approach, since the js frameworks make moving pieces of DOM around relatively easy.
- get checked items' rows
- get index of {top}-most checked item
- remove rows & insert them into table at {index-1}
- (of course top might be bottom, and index-1 is more complex depending on direction and whether or not we're at the extreme end already)
OTHER TIPS
This looks like a multi-keyed sorting task. You could use something like jQuery UI's Sortable interface. Your sort condition would be something like: a.selected <=> b.selected && a.index <=> b.index.
Disregard: You want to use the Fisher Yates Shuffle algorithm.