ADVERTISEMENT
ADVERTISEMENT

JavaScript: How to append something to an array?

Learn how to append something to an array in JavaScript?
Submitted by Pratishtha Saxena, on April 30, 2022

In JavaScript there are various ways to append something to an array or to append two arrays.

  1. Using push() method
    array_1.push('121','John')
  2. Using spread operator
    var array_3 = [...array_1,...array_2] 
  3. Using concat() method
    var array_3 =array_1.concat(array_2)

There can be many more ways to do so but these are some most common and easy ways to append something to an array. Let's see how.

Example 1:

var array = ['Dog', 'Cat', '526']
array.push('121', 'John') // using push
console.log(array)

Output:

(5) ['Dog', 'Cat', '526', '121', 'John']

Example 2:

var array_1 = ["Birds", "Fishes"]
var array_2 = ["Animals", "Dinosaurs"]

// using spread operator
var array_3 = [...array_1, ...array_2]

console.log(array_3)

Output:

(4) ['Birds', 'Fishes', 'Animals', 'Dinosaurs']

Example 3:

var states = ["MP", "UP", "Gujrat", "Rajasthan"]
var unionTerritory = ["Puducherry", "Chandigarh", "Andaman & Nicobar Island", "Lakshadweep"]

// using concat
var India = states.concat(unionTerritory)

console.log(India)

Output:

(8) ['MP', 'UP', 'Gujrat', 'Rajasthan', 'Puducherry', 'Chandigarh', 'Andaman & Nicobar Island', 'Lakshadweep']

JavaScript Examples »


ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.