To push multiple items to an array in JavaScript we simply can use the JavaScript Array push() method with the items separated by a commas.
someArray.push("d","e","f");
Let’s show this with a simple example.
var someArray = ["a","b","c"];
someArray.push("d","e",true,1);
console.log(someArray);
#Output
['a', 'b', 'c', 'd', 'e', true, 1]
Push Multiple Items to Array in JavaScript if They Do Not Already Exist in the Array
We can use JavaScript to add multiple items to an array if they do not already exist in the array by making use of the indexOf() and push() methods.
First let’s see how to add a single item to an array if it does not exist in the array.
var someArray = ["a","b","c"];
if( someArray.indexOf("d") == -1 ){
someArray.push("d");
}
console.log(someArray);
#Output
['a', 'b', 'c', 'd']
In the code above, we simply have an if-else conditional statement that checks whether the item is in the array using the indexOf() method. If the item is not in the array, then the number -1 will be returned. And if that is the case, we can then use the push() method to add the new item to the array.
Since we want to push multiple items to an array, we simply need to add a loop to loop through all the items we want to push. We will remove any items that are already in the array, and then push the items at the end.
var someArray = ["a","b","c"];
var itemsToAdd = ["d","e","a","f"];
for( var i = 0; i
Let's put this code in a function to make things simpler.
function addMultipleItems(arr,items){
for( var i = 0; i
In our function above, the user simply needs to give the function the array they want to check, and the items they want to add.
Now let's test this function out.
function addMultipleItems(arr,items){
for( var i = 0; i
Remember that with the indexOf() method, characters are case-sensitive. So you will notice that in the example above, "Hello" was added to our array even though "hello" was already in it.
Hopefully this article has been useful in helping you understand how to push multiple items to an array in JavaScript.