Arrays and objects are fundamental constructs in JavaScript. Often, you need to add objects dynamically into arrays as the data changes. In this comprehensive guide, we will explore three methods to push objects into JavaScript arrays – push(), unshift(), and splice().

Introduction to Arrays and Objects

An array represents an ordered collection of values. Arrays can include values of any data type – numbers, strings, booleans, functions, objects, and even other arrays.

let fruits = [‘Apple‘, ‘Banana‘, ‘Orange‘]; 
let mixed = [1, ‘Hello‘, true, {name: ‘John‘}]; 

Objects are collections of key-value pairs used to represent real-world things. The keys act as identifiers while values can be of any data type.

let person = {
  name: ‘John‘,
  age: 30  
};

Why add objects into arrays? We may need to represent real-world data as lists of objects. For example, a list of persons, products in a shopping cart, or chat messages.

Array push() Method

The fundamental method to add elements to an array is push(). As per the MDN docs:

The push() method adds one or more elements to the end of an array and returns the new length of the array.

Push Single Object Example

let fruits = [‘Apple‘, ‘Mango‘];

let fruitObj = {name: ‘Banana‘};

fruits.push(fruitObj); 

console.log(fruits); // [‘Apple‘, ‘Mango‘, {name: ‘Banana‘}]

The push method appends the fruitObj to the end of the fruits array.

Push Multiple Objects

push() can append multiple objects by passing them as arguments:

let cart = [];

cart.push(
  {id: 1, product: ‘Phone‘},
  {id: 2, product: ‘Tablet‘}
);

console.log(cart); 
/*
[
  {id: 1, product: ‘Phone‘},
  {id: 2, product: ‘Tablet‘}  
]
*/

This appends both product objects to the shopping cart array.

Array unshift() Method

While push() appends elements to the end of an array, unshift() can append elements to the beginning.

let nums = [2, 3, 4];

nums.unshift(1);

console.log(nums); // [1, 2, 3, 4] 

We can pass multiple items as well:

let teams = [‘Blue‘, ‘Yellow‘];

teams.unshift(‘Green‘, ‘Red‘);

console.log(teams); // [‘Green‘, ‘Red‘, ‘Blue‘, ‘Yellow‘]

Just like push(), unshift() also modifies the original array. But it inserts items at the start instead of the end.

Array splice() Method

The splice() method can insert and/or delete array elements. We can utilize it to insert one or more objects at any index within an array:

let months = [‘Jan‘, ‘Mar‘, ‘Apr‘]; 

months.splice(1, 0, ‘Feb‘);

console.log(months); // [‘Jan‘, ‘Feb‘, ‘Mar‘, ‘Apr‘]

In the above example:

  • First arg – Insert at index 1
  • Second arg – Delete 0 elements
  • Final arg – Insert ‘Feb‘

This inserts ‘Feb‘ at index 1 without deleting anything.

We can insert multiple items like this:

let rows = [1, 3, 4];

rows.splice(1, 0, 2, 5); 

console.log(rows); // [1, 2, 5, 3, 4]

This approach gives us precise control over where new objects get inserted into an array.

Array Insertion Methods

Credit: UnDraw

Comparing the Methods

While all three methods can append objects, there are some key differences:

push() unshift() splice()
Insertion Index End of array Start of array Any index
Inserts Copies No No Yes
Returns New array length New array length Deleted elements
Can delete No No Yes

So in summary:

  • push() appends efficiently to the end
  • unshift() inserts items at the start
  • splice() lets us insert anywhere
    • Also lets us delete elements
    • Inserts copies of objects

Understanding these distinctions enables us to pick the right tool for the job.

Performance Benchmarks

Adding elements has different performance based on the size of the array and the method used.

Let‘s analyze average timings empirically with a simple benchmark script:

// Test array with 10000 elements  

let arr = Array(10000).fill(1);

let testPush = () => {
  arr.push(1);
};

let testUnshift = () => {
  arr.unshift(1);  
};

let testSplice = () =>  {
  arr.splice(100, 0, 1);  
};

console.time(‘push‘);
testPush();
console.timeEnd(‘push‘);

console.time(‘unshift‘);
testUnshift();
console.timeEnd(‘unshift‘); 

console.time(‘splice‘);
testSplice(); 
console.timeEnd(‘splice‘);

Run this script a few times and compare average times.

Results:

Array Insertion Time Complexity

We see push() is faster than unshift(), while splice() is slowest since it has to insert an element in the middle of the array.

So for performance critical applications, push() works best for appending objects to array ends.

Immutability Matters

All the above methods modify the original array instead of creating new ones. Observe:

let colors = [‘red‘];
let newColors = colors.push(‘blue‘); 

console.log(newColors); // 2
console.log(colors); // [‘red‘, ‘blue‘]

This mutates colors. In some cases, mutability causes bugs if different parts of code reference the same array.

For safety, we can take an immutable approach by not modifying the original:

let colors = [‘red‘];
let newColors = [...colors, ‘blue‘]; 

console.log(colors); // [‘red‘] 
console.log(newColors); // [‘red‘, ‘blue‘]

Here we created a new newColors array instead of modifying colors. This immutable pattern prevents side effects elsewhere in code.

Alternatives with Spread and Array.from()

We have additional alternatives to insert into arrays without mutating them:

Spread syntax:

let oldArray = [1, 2];
let newArray = [0, ...oldArray, 3]; // [0, 1, 2, 3]

Array.from()

Converts iterable objects like sets into arrays:

let set = new Set([1, 2]);
let arr = Array.from(set); // [1, 2]

So in summary, push() / unshift() / splice() mutate existing arrays, while spread and Array.from() create new immutable ones.

Conclusion

  • Use the push() method to simply append objects to the end of an array.
  • To insert objects at the start, prefer the unshift() method instead.
  • Utilize splice() to insert objects at specific indices.
  • Understand the performance tradeoffs with large arrays.
  • Consider immutability with the spread syntax and Array.from().

I hope this guide gives you a comprehensive overview of how to dynamically push objects into arrays in JavaScript! Let me know if you have any other questions.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *