And*_*ade 5 javascript sorting algorithm indexing
假设我有一个索引的对象数组,例如包含流行民歌的行;)
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"}
];
Run Code Online (Sandbox Code Playgroud)
我的比较器将根据每个对象的索引显示视图中的对象.我希望能够在这个数组上执行三个任务:
任务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"}
];
Run Code Online (Sandbox Code Playgroud)
任务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"}
];
Run Code Online (Sandbox Code Playgroud)
任务3)重新索引删除
从数组中删除对象并重新索引数组中的所有项.因此,例如,如果删除索引为"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"}
];
Run Code Online (Sandbox Code Playgroud)
我没有CS学位所以我有点难以理解什么算法可以帮助我处理这个问题.有人能指出我正确的方向吗?
我正在使用javascript,所以如果有人知道上述任何事情,我会全神贯注.
dav*_*vin 10
我会完全简化你的整个结构:
使用本机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"]
Run Code Online (Sandbox Code Playgroud)
等等