Every computer science student must have come across the concept of arrays in their school or college. Arrays are a set of homogenous data values under the same name.
Array helps in implementing data structures like the stack, queues, and many more. Here we'll go through some methods and functions to push or add an element/object to an array in JavaScript.
Adding/Pushing an object to an array
There are numerous ways and methods in JavaScript for adding or pushing elements in an array. To achieve it, we'll be using the following functions/methods:
Method 1: Using push() function
The push() method performs the insertion operation in an array. It adds the items or objects at the end of the array.
Syntax:
array.push(objectName)
Code:
<html>
<head>
<meta charset="utf-8">
<title>Push an Object to an Array in JavaScript</title>
</head>
<body>
<p id="myarray"></p>
</body>
<script>
//adding a single object to the array
let a = ["Banana", "Orange", "Apple", "Mango"]; // Array
let ob = { Name: 'Jack', Age: 25, Role: 'CEO' }; // Object
a.push(ob);
console.log(a); // expected output- [{Name: 'Jack', Age: 25, Role: 'CEO'}]
document.getElementById("myarray").innerHTML = JSON.stringify(a);
</script>
</html>
Output:
Here, the object ob gets pushed to array A ( to the end of the array).
The push() method supports the insertion of multiple values as arguments. It also returns the number of arguments passed.
Code:
//adding a single object to the array
let array = ["Banana", "Orange", "Apple", "Mango"]; // Array
let obj = { Name: 'Joy', Age: 34, Designation: 'CEO' }; // Object One
let obj2 = { Name: 'Rahul', Age: 35, Designation: 'Director' }; // Object Two
array.push(obj,obj2);
console.log(array);
document.write('Final Array: ' + JSON.stringify(array));
Output:
Method 2: Using splice() function
This method can perform both insertion and deletion in an array.
Syntax:
array.splice(index, how many, item 1, ....., item n)
Here,
index- The starting index
how many- the number of elements to delete
item 1,...item n-the elements to insert
Code:
//adding a single object to the array
const letters = ["B", "O", "A", "M"]; // Array
// At position 2, add 2 elements:
letters.splice(2, 0, "L", "K");
document.write('Final Array: ' + JSON.stringify(letters));
Output:
The splice() method inserts items from a specified location as shown in the above example.
Method 3: Using unshift() function
This method performs an insertion operation at the beginning of an array. It allows the insertion of multiple values or objects.
Syntax:
array.unshift(item 1, item 2, ..., item n)
Here, item 1, item 2, ..., item n are the elements or items to be added.
Code:
const alphabets = ["A", "B", "C", "D"];
alphabets.unshift("E", "F");
document.write('Final Array: ' + JSON.stringify(alphabets));
Output:
Method 4: Using concat() function
The concat() method concatenates or merges two or more arrays and returns a new array(The elements of all the arrays are inside the new array).
Syntax:
concat(array 1, array 2.....array n)
Here, the arguments- array 1, array 2.....array n will concatenate in a single array.
Code:
const arr = ['A','B'];
const obj1 = { Name: 'Rahul', Age: 35, Designation: 'Director' };
const obj2 = { Name: 'Joy', Age: 34, Designation: 'CEO' };
const arr3 = arr.concat(obj1, obj2);
console.log(arr3);
document.write('Final Array: ' + JSON.stringify(arr3));
Output:
Here, the objects ob1 and ob2 got concatenated.
Difference between push(), splice(), and unshift():
push() method | splice() method | unshift() method | concat() method |
---|---|---|---|
Inserts an item or object at the end of an array. | Can perform both insertion and deletion operations in an array at any specified index. | Inserts an item or object at the beginning of an array. | Concatenates one or more arrays and returns a new array that contains the combined array. |
The push() method overwrites the original array. | The splice() method also overwrites the original array. | The unshift() method also overwrites the original array | The concat() method does not alter the original array. |
The push() is an inbuilt function of JavaScript. | The splice() is also an inbuilt function of JavaScript. | The unshift() is also an inbuilt function of JavaScript. | The concat() is also an inbuilt function of JavaScript. |
The push() method inserts item at the end of the array resulting in the increase of the array size by 1 | The splice() method inserts or deletes the items of the array, and shifts the elements to right from the specified index. | The unshift() method inserts elements from the 0th index, and shifts all the elements to the right. | The concat() method merge the arrays in order of the passed arguments(arrays). |
Conclusion:
Concluding the article we find that:
- There are more than one method for adding an object to an array in JavaScript.
- The methods/functions described above are- push(), splice(), unshift(), and concate().
- The push() method inserts element at the end of the array, the splice function at the specified location, and the unshift() method at the beginning of the array.
- The concat() method forms a new array by merging two or more arrays that are passed as argument.
- Differences between these methods/functions are also mentioned above.