How To Append To An Array in Javascript?

JavaScript Append To Array

Different values such as strings, numbers or objects can be appended to an array in javascript in different ways.

Append A Single Value To An Array in Javascript

The Array.prototype.push method can be used to append values to an array in javascript.

//Defined Array
var arr = ["A","B","C"];

//Appending New Value to the defined array
arr.push("D");

//Printing the Array in Console
console.log(arr);

Javascript Push Method To Append A Value To An Array

Appending Multiple Values To An Javascript Array

You can also append multiple values using this method.

//Appending Multiple values to an Array
arr.push("D","E","F");

Appending Multiple Values To An Array In Javascript

Concatenating Javascript Arrays (Appending One Array To Another)

One or more arrays can also be appended to an existing array in Javascript. This is basically called as the concatenation of arrays. Therefore, the firstArray.concat(secondArray) method is used in this case.

//Defining the First Array
arr1 = ["A","B","C"];

//Defining the Second Array
arr2 = ["D","E","F"];

//Appending Second Array To First (Concatenation)
arr1.concat(arr2);

//Printing the Concatenated Array in Console
console.log(arr);

Javascript Array Concatenation

Appending Values At The Start of Array (Prepending)

//A Defined Array
arr = ["B","C","D"];

//Adding A New Value At the Start of Array
arr.unshift("A");

//The New Array Output
console.log(arr);

Prepending JavaScript Array Append To Start

Likewise, multiple values can also be appended using this method at the start of a JavaScript Array as we can append multiple values to the end of an array using the array.push() method.

Other Different Ways For Javascript Elements To An Javascript Array

There are some more different ways to append or prAppendingepend the things to Javascript Arrays.

arr[arr.length] = newValue;

Example.

a = ["A","B","C"];
a[a.length] = "D";
console.log(a);

Non Common Method To Append Elements To An Javascript Array

Two arrays can also be appended or concatenated using Array.prototype.push.apply method.

arr1 = [1,2,3];
arr2 = [4,5,6];

Array.prototype.push.apply(arr1, arr2);
console.log(arr1);

Array.prototype.push.apply Javascript Concatenation Method


Subscribe To WTMatter

Leave a Reply

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