title: Insert item inside an Array

tip-number: 00 tip-username: loverajoel tip-username-profile: https://github.com/loverajoel tip-tldr: Inserting an item into an existing array is a daily common task. You can add elements to the end of an array using push, to the beginning using unshift, or to the middle using splice. tip-writer-support: https://www.coinbase.com/loverajoel

Inserting an item into an existing array

Inserting an item into an existing array is a daily common task. You can add elements to the end of an array using push, to the beginning using unshift, or to the middle using splice.

Those are known methods, but it doesn’t mean there isn’t a more performant way. Here we go:

Adding an element at the end

Adding an element at the end of the array is easy with push(), but it can be done in different ways.

var arr = [1, 2, 3, 4, 5];var arr2 = [];arr.push(6);arr[arr.length] = 6;arr2 = arr.concat([6]);

Both first methods modify the original array. Don’t believe me? Check the jsperf

Performance on mobile :

Android (v4.2.2)

  1. arr.push(6); and arr[arr.length] = 6; have the same performance // 3 319 694 ops/sec
  2. arr2 = arr.concat([6]); 50.61 % slower than the other two methods

Chrome Mobile (v33.0.0)

  1. arr[arr.length] = 6; // 6 125 975 ops/sec
  2. arr.push(6); 66.74 % slower
  3. arr2 = arr.concat([6]); 87.63 % slower

Safari Mobile (v9)

  1. arr[arr.length] = 6; // 7 452 898 ops/sec