In vanilla JavaScript, you can use the Array.push()
method to add new items to an array. This method appends one or more items at the end of the array and returns the new length.
Here is an example:
const fruits = ['Orange', 'Mango', 'Banana'];
// add more fruits
fruits.push('Apple', 'Lemon');
console.log(fruits);
// ['Orange', 'Mango', 'Banana', 'Apple', 'Lemon']
If you want to append items to the beginning of an array, use the Array.unshift()
method instead. This method works similar to Array.push()
except that the given items are added at the start of the array:
const fruits = ['Orange', 'Mango', 'Banana'];
// add more fruits
fruits.unshift('Kiwi', 'Lemon');
console.log(fruits);
// ['Kiwi', 'Lemon', 'Orange', 'Mango', 'Banana']
Adding item at a specific index
To add a new item at a particular index in an array, you can use the Array.splice() method. This method adds new items at the specified starting index and returns the removed items if any.
Here is an example that demonstrates how to add a new item at 3rd index in an array using Array.splice()
:
const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];
const removed = fruits.splice(2, 0, 'Cherry');
console.log(fruits); // ['Apple', 'Orange', 'Cherry', 'Mango', 'Banana']
console.log(removed); // []
Merging two arrays
What if you want to add all items of an array to another array? You can use the Array.concat()
method to merge two or more arrays together. This method takes one or more arrays as input and merges all subsequent arrays into the first:
const fruits = ['Orange', 'Mango', 'Banana'];
const moreFruits = ['Kiwi', 'Lemon'];
// merge all fruits
const allFruits = fruits.concat(moreFruits);
console.log(allFruits);
// ['Orange', 'Mango', 'Banana', 'Kiwi', 'Lemon']
The Array.concat()
method doesn't change the original arrays. Instead, it always returns a new array.
Take a look at this article to learn more about JavaScript arrays and how to use them to store multiple pieces of information in one single variable.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.