Push a string to an empty Array without it becoming a sub array

158 views Asked by At

I have a sad array which consists of a string.

var sadArray = ["I am a happy sentence."];

I would like to take this sentence out of the sad array (because its not a sad sentence :) ) and move it into the happy array

var happyArray = [];

This is the way I am trying to go about this

happyArray.push(sadArray);

However, the result of this is that the whole sadArray not just the sentence inside it, gets pushed to the happyArray resulting in a 2d array

console.log(happyArray); //returns [ [ "I am a happy sentence." ] ]

How can i achieve this outcome?:

console.log(sadArray); //returns empty array because i removed the happy sentence from it

console.log(happyArray); //returns ["I am a happy sentence."]

1

There are 1 answers

0
Ankit Agarwal On BEST ANSWER

The push works perfectly fine. Check the code, if you push the array again into another array then you will get [[welcome to the world people]] like in anotherArray. Otherwise, the first push to myArray simply works fine.

var myString = "welcome to the world people";
var myArray = [];
myArray.push(myString);
console.log(myArray);

var anotherArray = [];
anotherArray.push(myArray);
console.log(anotherArray);