-1

How do I push array into a new Array. For example

var arr = ['one','two','three'];
var newArr = [];

Now I want newArr[0] = ['one','two','three']

I have tried using push function but it pushes all the elements of arr into newArr. I want to push the entire arr as it is in newArr

jainilvachhani
  • 708
  • 6
  • 13
  • 2
    `newArr.push(arr)` does work like you intend it to: https://jsfiddle.net/msw3p17b/ – TiiJ7 Sep 07 '20 at 11:41
  • Duplicate of https://stackoverflow.com/questions/351409/how-to-append-something-to-an-array – str Sep 07 '20 at 11:43

3 Answers3

3
var arr = ['one','two','three'];
var newArr = [];
newArr.push(arr); //<-- add entire original array as first key of new array
Mitya
  • 33,629
  • 9
  • 60
  • 107
  • 3
    IDK why this is downvoted, I just upvoted it because it is the right answer. @jainilvachhani maybe your question isn't clear? – Dalibor Sep 07 '20 at 11:42
  • 1
    How you can add something to an array has been answered many times already. There is really no need to answer it again. – str Sep 07 '20 at 11:44
  • 1
    That does not, in itself, make my answer poor or worthy of downvoting. It's an issue inherant in SO's model that, when answering, one cannot always know whether the same question has been asked (far less answered) before - once, or many times. – Mitya Sep 07 '20 at 11:52
  • [Should we downvote answers to obvious duplicate questions?](https://meta.stackexchange.com/questions/202895/should-we-downvote-answers-to-obvious-duplicate-questions) Having yet another answer showing how to add something to an array is definitely not useful in my eyes. And given your rep, it should not be a surprise to you that this question already has plenty of duplicates. – str Sep 07 '20 at 11:59
  • @Dalibor Yes, you do. – Mitya Sep 07 '20 at 12:58
  • @str Then it comes down to what high-rep users are expected to *suspect* are previously-asked/answered questions. Creating an array and wanting to put it in another array doesn't, to my mind, sound like an everyday thing (if the question was "how do I delete an item from an array" or "how do I return a response from an AJAX request", then, sure.). But, sure, I agree with your sentiment in general. – Mitya Sep 07 '20 at 13:03
2

You can write:

newArr[0] = ['one','two','three'];

And this will work. Or use variable:

 newArr[0] = arr;

Also, array methods push or unshift will the same way in your situation work:

newArr.push(arr);
Yevhenii Shlapak
  • 588
  • 2
  • 4
  • 13
2

Others have answered, so I guess your question is not really clear.

As you put your question, first and only element of newArray should be the arr array, then you use

newArr.push(arr);

as Mitya and Tiij7 said.

However, maybe you meant you want to join (concat) 2 arrays in a new array? Then you would use:

var arr3 = [].concat(arr, newArr);

or

var arr3 = [...arr, ...newArr];

Or you just wanted to clone the initial array? Then use

var newArr = [...arr];
Dalibor
  • 1,430
  • 18
  • 42