Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining arrays in JS

Tags:

javascript

If you have 2 arrays classical and pop:

classical=["Beethoven","Mozart","Tchaikovsky"];
pop=["Beatles","Corrs","Fleetwood Mac","Status Quo"];

Why is that when you set all=classical+pop it gives sets character in the array elements an individual character?

How do you correct this without retyping i.e. all=["Beethoven","Mozart","Tchaikovsky","Beatles"...]

Many thanks in advance.

like image 726
methuselah Avatar asked Dec 21 '22 05:12

methuselah


2 Answers

Use the Array class concat() method to combine them on a new variable:

var all = classical.concat(pop);
like image 147
mattacular Avatar answered Dec 24 '22 02:12

mattacular


+ is first converting both arrays to string, and then adding the strings. For this you need to use concat method.

> classical=["Beethoven","Mozart","Tchaikovsky"];
["Beethoven", "Mozart", "Tchaikovsky"]
> pop=["Beatles","Corrs","Fleetwood Mac","Status Quo"];
["Beatles", "Corrs", "Fleetwood Mac", "Status Quo"]
> all = classical.concat(pop)
["Beethoven", "Mozart", "Tchaikovsky", "Beatles", "Corrs", "Fleetwood Mac", "Status Quo"]
like image 40
taskinoor Avatar answered Dec 24 '22 01:12

taskinoor