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

前端 未结 1 680
灰色年华
灰色年华 2021-01-19 00:13

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          


        
相关标签:
1条回答
  • 2021-01-19 00:44

    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 讨论(0)
提交回复
热议问题