Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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 oninsert// lets insertsecondin the natural place

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

// reindex ondelete// lets delete'third'

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

etc.

Post a Comment for "Algorithm To Re-index An Array Of Objects After Insertion Or Drag 'n' Drop Order Change"