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

后端 未结 20 2142
灰色年华
灰色年华 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

    What you want is the splice function on the native array object.

    arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert).

    In this example we will create an array and add an element to it into index 2:

    var arr = [];
    arr[0] = "Jani";
    arr[1] = "Hege";
    arr[2] = "Stale";
    arr[3] = "Kai Jim";
    arr[4] = "Borge";
    
    console.log(arr.join());
    arr.splice(2, 0, "Lene");
    console.log(arr.join());

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题