How to insert an item into an array at a specific index (JavaScript)?

后端 未结 20 2123
灰色年华
灰色年华 2020-11-21 07:05

I am looking for a JavaScript array insert method, in the style of:

arr.insert(index, item)

Preferably in jQuery, but any JavaScript implem

20条回答
  •  日久生厌
    2020-11-21 08:07

    Solutions & Performance

    Today (2020.04.24) I perform tests for chosen solutions for big and small arrays . I tested them on MacOs High Sierra 10.13.6 on Chrome 81.0, Safari 13.1, Firefox 75.0.

    Conclusions

    For all browsers

    • surprisingly for small arrays non-in-place solutions based on slice and reduce (D,E,F) are usually 10x-100x faster than in-place solutions
    • for big arrays the in-place-solutions based on splice (AI,BI,CI) was fastest (sometimes ~100x - but it depends of array size)
    • for small arrays BI solution was slowest
    • for big arrays E solution was slowest

    Details

    Tests was divided into two groups: in-place solutions (AI,BI,CI) and non-in-place solutions (D,E,F) and was perform for two cases

    • test for array with 10 elements - you can run it HERE
    • test for array with 1.000.000 elements - you can run it HERE

    Tested code is presented in below snippet

    jsfiddle

    function AI(arr, i, el) {
      arr.splice(i, 0, el);
      return arr;
    }
    
    function BI(arr, i, el) {
      Array.prototype.splice.apply(arr, [i, 0, el]);
      return arr;
    }
    
    function CI(arr, i, el) {
      Array.prototype.splice.call(arr, i, 0, el);
      return arr;
    }
    
    function D(arr, i, el) {
      return arr.slice(0, i).concat(el, arr.slice(i));
    }
    
    function E(arr, i, el) {
      return [...arr.slice(0, i), el, ...arr.slice(i)]
    }
    
    function F(arr, i, el) {
      return arr.reduce((s, a, j)=> (j-i ? s.push(a) : s.push(el, a), s), []);
    }
    
    
    
    // -------------
    // TEST
    // -------------
    
    let arr = ["a", "b", "c", "d", "e", "f"];
    
    let log = (n, f) => {
      let a = f([...arr], 3, "NEW");
      console.log(`${n}: [${a}]`);
    };
    
    log('AI', AI);
    log('BI', BI);
    log('CI', CI);
    log('D', D);
    log('E', E);
    log('F', F);
    This snippet only presents tested code (it not perform tests)

    Example results for small array on chrome are below

提交回复
热议问题