Array.push() appends one or more elements to the end of an array and modifies the original array, returning the new length. Use array.push(...otherArray) to add all elements from another array.

Spread operator (...) creates a new array by merging two arrays without modifying the originals.

let array1: number[] = [1, 2];
let array2: number[] = [3, 4];
let mergedArray: number[] = [...array1, ...array2]; // [1, 2, 3, 4]

Array.concat() returns a new array by combining the original array with one or more arrays or values.

let mergedArray = array1.concat(array2); // [1, 2, 3, 4]

Use push(...otherArray) for in-place modification, spread operator or concat() for creating new arrays.

Use the concat function, like so:

var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayA.concat(arrayB);

The value of newArray will be [1, 2, 3, 4] (arrayA and arrayB remain unchanged; concat creates and returns a new array for the result).

Answer from WiseGuyEh on Stack Overflow
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjavascript โ€บ can you only add an array to another array?
r/learnjavascript on Reddit: Can you only add an array to another array?
October 4, 2022 -

Hi there!

I'm new to JavaScript and was learning about arrays today and saw that the instructor only added an array to another array. Is it possible to add something that is not an array into an array? Iyes, how can I do that?

Thanks in advance!

Discussions

Three ways to append an item to an array (Mutative)
myArray = [...myArray, 'Pig'] :) More on reddit.com
๐ŸŒ r/learnjavascript
33
131
September 1, 2022
How to append something to an array?
How do I append an object (such as a string or number) to an array in JavaScript? More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to push an object into an array with Typescript - Stack Overflow
I have an array named Dish and have a form. After the form is submitted, data pushes to dish. I have tried to use the push method to add that into an array, but it throws an error. How I can do tha... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Can you only add an array to another array?
Push: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push const numbers = [1, 2, 3]; numbers.push(4); console.log(numbers); // [1, 2, 3, 4] const arrays = [[1, 2], [3, 4]]; arrays.push([5, 6]); console.log(arrays); // [[1, 2], [3, 4], [5, 6]] const whatever = [{ name: 'Sue' }, false, null]; whatever.push('eleventy'); console.log(whatever); // [{ name: 'Sue' }, false, null, 'eleventy'] Concat: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat const odds = [1, 3]; const evens = [2, 4]; const all = odds.concat(evens); console.log(odds); // [1, 3] console.log(evens); // [2, 4] console.log(all); // [1, 3, 2, 4] Spread operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax const odds = [1, 3]; const evens = [2, 4]; const all = [...odds, ...evens]; console.log(odds); // [1, 3] console.log(evens); // [2, 4] console.log(all); // [1, 3, 2, 4] More on reddit.com
๐ŸŒ r/learnjavascript
9
6
October 4, 2022
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ Array โ€บ push
Array.prototype.push() - JavaScript | MDN
The element(s) to add to the end of the array. The new length property of the object upon which the method was called. The push() method appends values to an array.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ home โ€บ typescript โ€บ typescript array push method
TypeScript Array Push Method
December 18, 2016 - Learn how to use the Array Push method in TypeScript to add elements to an array efficiently. Discover examples and best practices.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ typescript โ€บ typescript-array-push-method
TypeScript Array push() Method - GeeksforGeeks
July 12, 2024 - In this example, we add a single element to an array. ... let numbers: number[] = [11, 89, 23, 7, 98]; let newLength: number = numbers.push(8); console.log(numbers); console.log(newLength); ... In this example, we add multiple elements to an array.
๐ŸŒ
CodyHouse
codyhouse.co โ€บ blog โ€บ post โ€บ javascript-append-to-array
JavaScript quick tip - append to array with examples | CodyHouse
As the push method, unshift modifies the original array and returns the new length of the modified array. Another method you can use to merge two arrays is the concat method.
๐ŸŒ
HowToDoInJava
howtodoinjava.com โ€บ home โ€บ typescript โ€บ typescript โ€“ how to add items to array
TypeScript - How to Add Items to Array
July 26, 2023 - Learn to add or append or push new items into an array in TypeScript. Also, learn to append or merge an array into a specified array.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjavascript โ€บ three ways to append an item to an array (mutative)
r/learnjavascript on Reddit: Three ways to append an item to an array (Mutative)
September 1, 2022 - Questions and posts about frontend development in general are welcome, as are all posts pertaining to JavaScript on the backend. ... "unrolling the entire array into a new array and paying for a complete new allocation from scratch while also faulting several kinds of copy should be best practice," says the person who doesn't know that a
Find elsewhere
๐ŸŒ
SamanthaMing
samanthaming.com โ€บ tidbits โ€บ 87-5-ways-to-append-item-to-array
5 Way to Append Item to Array in JavaScript | SamanthaMing.com
5 ways to add an item to the end of an array. Push, Splice, and Length will mutate the original array. Concat and Spread won't and will return a new array...
Top answer
1 of 16
5428

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

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

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

console.log(arr);
Run code snippetEdit code snippet Hide Results Copy to answer Expand


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

Copy// 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]);
}
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Note that the push() method returns the updated length of the array.


Update

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

Copyvar 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);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

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.

Copyvar arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

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 or prepended, compliant with the spirit of functional programming.

Copyconst arr1 = [
  "Hi",
  "Hello",
  "Bonjour",
];
const arr2 = [
  "Ciao",
  "Hej",
  "Merhaba",
];

const newArr1 = [
  ...arr1,
  "Salut",
];
const newArr2 = [
  "Salut",
  ...arr2,
];
const newArr3 = [
  ...arr1,
  ...arr2,
];

console.log(newArr1, newArr2, newArr3);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 16
1122

If you're only appending a single variable, then push() works just fine. If you need to append another array, use concat():

Copyvar ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];

var ar3 = ar1.concat(ar2);

alert(ar1);
alert(ar2);
alert(ar3);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

The concat does not affect ar1 and ar2 unless reassigned, for example:

Copyvar ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];

ar1 = ar1.concat(ar2);
alert(ar1);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

There is a lot of great information on JavaScript Reference.

Top answer
1 of 5
34
let myArray = [];
let commentData = {} as Dish;
commentData.id = 3;
commentData.name = 'something';
myArray.push(commentData);

It will work...

2 of 5
10

#Answer

Answer on how to push Comment (object) into Dish.comments (array) in TypeScript.


export interface Dish {
   id: number;
   name: string;
   image: string;
   category: string;
   label: string;
   price: string;
   featured: boolean;
   description: string;
   // comments: Comment[]; // remove this
   comments: Array<Comment>; // <--- change to this. everytime you want to add array use Array<YourInterface>
}

export interface Comment {
   rating: number;
   comment: string;
   author: string;
   date: string;
}

dish.comments.push(commentData);

View live code on TypeScript Playground and click RUN.

As you see in the above code. You need to change Comment[] into Array<Comment>.

#Explanation

Generic Type Variables

Array<T> or Array<Type>

You may already be familiar with this style of type from other languages such as Java and C#.

We have Generic Type Variables in typescript too.

Another way to use Generic Type Variables:

Here's an example of an array with multiple types:


let x: Array<string | number>
x = ["hello", "world", 2]

This second version is common if your array consists of different types of objects. For example:

interface Boat {
  name: string
}

interface SpaceShip {
  code: number
}

interface Wagon {
  active: boolean
}

let inventory: Array<Boat | SpaceShip | Wagon> = [];

let boatData: Boat = {
  name: "Boat 1"
}

let spaceShipData: SpaceShip = {
  code: 1234
}

let wagonData: Wagon = {
  active: true
}

inventory.push(boatData);
inventory.push(spaceShipData);
inventory.push(wagonData);

console.log(inventory);

View live code on TypeScript Playground and click RUN.

You can learn more about Generic Type Variables here and here

๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ home โ€บ typescript โ€บ typescript array concat
TypeScript Array Concat
December 18, 2016 - Discover how to use the concat method in TypeScript to combine multiple arrays with examples and tips for effective usage.
๐ŸŒ
Medium
dpericich.medium.com โ€บ how-to-push-elements-to-a-typescript-array-ea9a899687f8
How to Push Elements to a TypeScript Array | by Daniel Pericich | Medium
June 12, 2022 - TypeScript has a special never type that applies to empty type declarations and errors when pushing items to the array. In this article we examine never and
๐ŸŒ
WebDevAssist
webdevassist.com โ€บ typescript โ€บ typescript-array-push
How to add elements to an Array in TypeScript
This method adds items to the end of an array and returns the length. In this post, we will learn how to use the push method with example. ... Where, e1, e2, etc. are elements to append to the array.
๐ŸŒ
W3Schools
w3schools.com โ€บ typescript โ€บ typescript_arrays.php
TypeScript Arrays
TypeScript has a specific syntax for typing arrays. Read more about arrays in our JavaScript Array chapter. const names: string[] = []; names.push("Dylan"); // no error // names.push(3); // Error: Argument of type 'number' is not assignable to parameter of type 'string'. Try it Yourself ยป
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-push-an-element-to-the-end-of-an-array-in-typescript
How to push an element to the end of an array in TypeScript
element1, element2, ... elementN: these are the elements we want to push to the array. There can be more than one elements. This method returns the new array length. ... Line 2โ€“5: We create some arrays in TypeScript and initialize them.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-add-one-or-more-elements-to-an-array-in-typescript
How to add one or more elements to an array in TypeScript
Similar to JavaScript, which is a subset of TypeScript, we can add elements to an array using the unshift() method.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ javascript-append-to-array-a-js-guide-to-the-push-method-2
JavaScript Append to Array: a JS Guide to the Push Method
April 19, 2021 - Sometimes you need to append one or more new values at the end of an array. In this situation the push() method is what you need. The push() method will add one or more arguments at the end of an array in JavaScript: let arr = [0, 1, 2, 3];
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ Array โ€บ concat
Array.prototype.concat() - JavaScript | MDN
Then, for each argument, its value will be concatenated into the array โ€” for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property Symbol.isConcatSpreadable set to a truthy value, each element of the argument will be independently added to the final array.