开发者

Algorithm to re-index an array of objects after insertion or drag 'n' drop order change

Assume I have an indexed array of objects, such as these containing lines of a popular folk song ;)

var lyrics = [
  {line : 2, words : "He's a lumberjack and he's okay"},
  {line : 1, words : "I'm a lumberjack and I'm okay"},
  {line : 3, words : "He sleeps all night and he works all day"}
];

My comparator will display the objects in the view according to each object's index. I want to be able to perform the three tasks on this array:

Task 1) Reindex on drag 'n drop

Re-arrange the order of the objects via drag and drop. Assume I already know how to implement drag and drop. Task example: Drag "He's a lumberjack and he's okay" from index "1" to after "I'm a lumberjack and I'm okay". "He's a lumberjack and he's okay" should now occupy index "2" and "I'm a lumberjack and I'm okay" should occupy index "1". The resulting array should be:

var lyrics = [
  {line : 1, words : "I'm a lumberjack and I'm okay"},
  {line : 2, words : "He's a lumberjack and he's okay"},
  {line : 3, words : "He sleeps all night and he works all day"}
];

Task 2) Re-index on insert

Add an object to any point in the array, reindexing all the items in the array. Task example: Add a "I sleep all night and I work all day" object as the second item in the array. The resulting array should be:

var lyrics = [
  {line : 1, words : "I'm a lumberjack and I'm okay"},
  {line : 2, words : "I sleep all night and I work all day"},
  {line : 3, words : "He's a lumberjack and he's okay"},
  {line : 4, words : "He sleeps all night and 开发者_如何学Che works all day"}
];

Task 3) Re-index on delete

Delete an object from an array and reindex all the items in the array. So for example, if object with index "3" were deleted, the resulting array should be:

var lyrics = [
  {line : 1, words : "I'm a lumberjack and I'm okay"},
  {line : 2, words : "I sleep all night and I work all day"},
  {line : 3, words : "He sleeps all night and he works all day"}
];

I don't have a CS degree so I'm kind of stumped on what algorithm would help me handle this. Can someone point me in the right direction?

I'm working with javascript, so if anyone knows anything that does the above, I'm all ears.


I would totally simplify your entire structure:

Use a native javascript array, instead of storing an extra key (line) use the javascript index as the key, which means javascript (if used properly) will manage it for you, and use less memory.

So we've got an array of strings:

var f = [];
f.push('first');
f.push('third');
f.push('fourth');

// reindex on insert
// lets insert second in the natural place

f.splice(1,0,'second'); // ["first", "second", "third", "fourth"]

// reindex on delete
// lets delete 'third'

f.splice(2,1); // ["first", "second", "fourth"]

etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜