Say for example I have an array
arr = [
1, 2, 3
4, 5, 6
]
Instead, I would like to use aliases for each line Ex.
var a = [ 1, 2, 3 ];
var b = [ 4, 5, 6 ];
Where
arr = [
a,
b
]
should be the same as the original arr.
Yet the current example gives back [ [1,2,3],[4,5,6] ] instead
How would I achieve something like this in javascript?
2 Answers 2
Use Array::concat():
var a = [ 1, 2, 3 ];
var b = [ 4, 5, 6 ];
var c = [ 7, 8, 9 ];
var arr = Array.concat(a,b,c);
alert(arr); // 1,2,3,4,5,6,7,8,9
answered Feb 1, 2015 at 4:47
bgoldst
35.6k6 gold badges44 silver badges64 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
"should be the same as the original arr." NO!!!
The
concat()method is used to join two or more arrays.This method does not change the existing arrays, but returns a new array, containing the values of the joined arrays.
var a = [ 1, 2, 3 ];
var b = [ 4, 5, 6 ];
arr = a.concat(b); //or Array.concat(a,b);
console.log(a);//[1,2,3]
console.log(b);//[4,5,6]
console.log(arr);//[1,2,3,4,5,6]
answered Feb 1, 2015 at 5:42
Vijay
3,0231 gold badge18 silver badges24 bronze badges
Comments
lang-js
arr = [ a, b ]work?arr = [a, b]results in[ [1,2,3],[4,5,6]]