How to append something to an array?

Total
0
Shares

How do I append an object (such as a string or number) to an array in JavaScript?


Solution

Use the Array.prototype.push method to append values to the end of an array:

_x000D_

_x000D_

// initialize array
var arr = [
  "Hi",
  "Hello",
  "Bonjour"
];

// append new value to the array
arr.push("Hola");

console.log(arr);

_x000D_

_x000D_

_x000D_


You can use the push() function to append more than one value to an array in a single call:

_x000D_

_x000D_

// initialize array
var arr = ["Hi", "Hello", "Bonjour", "Hola"];

// append multiple values to the array
arr.push("Salut", "Hey");

// display all values
for (var i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

_x000D_

_x000D_

_x000D_


Update

If you want to add the items of one array to another array, you can use firstArray.concat(secondArray):

_x000D_

_x000D_

var arr = [
  "apple",
  "banana",
  "cherry"
];

// Do not forget to assign the result as, unlike push, concat does not change the existing array
arr = arr.concat([
  "dragonfruit",
  "elderberry",
  "fig"
]);

console.log(arr);

_x000D_

_x000D_

_x000D_

Update

Just an addition to this answer if you want to prepend any value to the start of an array (i.e. first index) then you can use Array.prototype.unshift for this purpose.

_x000D_

_x000D_

var arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);

_x000D_

_x000D_

_x000D_

It also supports appending multiple values at once just like push.


Update

Another way with ES6 syntax is to return a new array with the spread syntax. This leaves the original array unchanged, but returns a new array with new items appended, compliant with the spirit of functional programming.

_x000D_

_x000D_

const arr = [
  "Hi",
  "Hello",
  "Bonjour",
];

const newArr = [
  ...arr,
  "Salut",
];

console.log(newArr);

_x000D_

_x000D_

_x000D_

Source: StackOverflow.com

Leave a Reply

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