-1

Given an array of integers, for example: [1,2,3,4,5], I need to be able to take the array and output the array twice. The final result should look like: [1,2,3,4,5,1,2,3,4,5]. This should be fairly simple, but getting stuck on comma separating the two arrays at the end.

var array = [1,2,3,4,5];
var final = [];
for(i = 1; i <= array.length; i++){
 final.push(i);
}
console.log(final+final);

This could also be re-written in a function, so you can pass any number of values, such as function concat(12345){}

user3438917
  • 417
  • 1
  • 7
  • 26

5 Answers5

2

You Can Add Same Array a.

Array.prototype.push.apply(a,a)
Shankar Shastri
  • 1,134
  • 11
  • 18
  • Note: this will _modify_ the input. Question does not specify if that's acceptable or not but it's something that bears bringing up. – VLAZ Sep 14 '16 at 15:36
1

This could also be re-written in a function.

The people creating javascript thought so too, so they created Array.prototype.concat() for you!

var array = [1,2,3,4,5];
var out = array.concat(array);
console.log(out);
baao
  • 71,625
  • 17
  • 143
  • 203
0

try this:

var new_array = array.concat(array)
Bartłomiej Gładys
  • 4,525
  • 1
  • 14
  • 24
0

Quickest way is to concat:

var array = [1, 2, 3, 4, 5];
var final = array.concat(array);
0

You can simply do by using Concat function in javascript.

Read more about this . Array Concat Example

Uzair
  • 714
  • 2
  • 6
  • 17