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 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 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