How to add multiple objects to a single array list in Javascript?

JavascriptFront End TechnologyObject Oriented Programming

There are many ways to add multiple objects to a single array list in Javascript. Let us look at some of them −

push()

To add multiple objects at the end of an array, you can repeatedly call push on it. For example,

Example

let arr = [];
arr.push(1);
arr.push(2);
console.log(arr);

Output

This will give the output −

[1, 2]

unshift()

To add multiple objects at the start of an array, you can repeatedly call unshift on it. For example,

Example

let arr = [];
arr.unshift(1);
arr.unshift(2);
console.log(arr);

Output

This will give the output −

[2, 1]

Using the spread operator

The spread operator can help you copy over one array into another. For example,

Example

let arr1 = [1, 2, 3];
let arr2 = ['hello', ...arr1, 'world];
console.log(arr2);

Output

This will give the output −

['hello', 1, 2, 3, 'world]
raja
Published on 02-Dec-2019 10:52:53
Advertisements