重建数组对象的算法:在插入或拖放顺序更改后重新索引。

5
假设我有一个包含对象的索引数组,例如这些包含流行民歌歌词的行;)
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"}
];

我的比较器将根据每个对象的索引在视图中显示对象。我想能够在此数组上执行以下三个任务:

任务1)拖放重新索引

通过拖放重新排列对象的顺序。假设我已经知道如何实现拖放操作。任务示例:将“他是伐木工人,他很好”从索引“1”拖到“我是伐木工人,我很好”的后面。现在,“他是伐木工人,他很好”应占据索引“2”,“我是伐木工人,我很好”应占据索引“1”。得到的数组应为:

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"}
];

任务2)插入时重新索引

在数组的任意位置添加一个对象,重新索引数组中的所有项。任务示例:在数组的第二个位置添加一个“我整晚睡觉,整天工作”的对象。结果数组应为:

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 he works all day"}
];

任务三) 删除后重新索引

从数组中删除一个对象,并重新对数组中的所有项目进行索引。例如,如果删除索引为“3”的对象,则结果数组应为:

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"}
];

我没有计算机科学学位,所以我不知道用什么算法来帮助我处理这个问题。有人可以指点我一下吗?

我正在使用javascript,如果有人知道如何做到上述的操作,欢迎告诉我。


你到底对什么感到困惑? - Marcin
1个回答

11

我会彻底简化你的整个结构:

使用本地 JavaScript 数组,而不是存储额外的键 (line),使用 JavaScript 索引作为键,这意味着 JavaScript(如果使用得当)将为您管理它,并使用更少的内存。

所以我们有了一个字符串数组:

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"]

等等其他内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接