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]
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]
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; }
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);
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]
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])
what you're looking for is:
var randomArr = [1,2,3];
var randomArr2 = [4,5,6];
var randomResult =randomArr.concat(randomArr2)
console.log(randomResult);