-1

Javascript arrays are not merging:

var randomArr = [1,2,3];
var randomArr2 = [4,5,6];

console.log(randomArr + randomArr2); // "1,2,34,5,6"

I get the result : 1,2,34,5,6
Why is that?

I expected [1,2,3] + [4,5,6] = [1,2,3,4,5,6]

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
SQUIGGER
  • 9
  • 1

5 Answers5

1

You want concat.

var randomArr = [1, 2, 3];
var randomArr2 = [4, 5, 6];

const res = randomArr.concat(randomArr2);

console.log(res);

You could alternatively concatenate the arrays into an empty array - this solution is more modular and avoids nesting of concat calls.

var randomArr = [1, 2, 3];
var randomArr2 = [4, 5, 6];
var randomArr3 = [7, 8, 9];

const res = [].concat(randomArr, randomArr2, randomArr3);

console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

You should use .concat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

let randomArr = [1,2,3];
let randomArr2 = [4,5,6];
let resultArray = randomArr.concat(randomArr2);
console.log(resultArray); 
tkore
  • 1,101
  • 12
  • 31
Alejandro
  • 104
  • 4
1

JavaScript doesn't support adding or appending Arrays in the way you're trying to. It converts them to Strings: "1,2,3" and "4,5,6" then appends the second to the first, thus "1,2,34,5,6".

You want to use Array.concat to merge the arrays:

var randomArr = [1,2,3];
var randomArr2 = [4,5,6];

console.log(randomArr.concat(randomArr2)); // [1,2,3,4,5,6]
Aaron
  • 2,049
  • 4
  • 28
  • 35
1

You can't concatinate ("merge") arrays by using a plus.

Use Array.prototype.concat():

console.log(randomStuff1.concat(randomStuff2))

Use the spread operator:

console.log([...randomStuff1, ...randomStuff2])
lforst
  • 41
  • 5
1

what you're looking for is:

var randomArr = [1,2,3];
var randomArr2 = [4,5,6];

var randomResult =randomArr.concat(randomArr2)
console.log(randomResult);
corrado4eyes
  • 283
  • 2
  • 11