Alfred M.
Alfred M.

Reputation: 189

Arrays: Combining them in such a way

So I am trying to combine two arrays but I think all that I've read here is different than what I want to achieve. So here are my initial arrays:

oldArray = ['name','age','address','number'];

firstArray = ['Peter Parker','16','Queens','123456789']; // this is dynamic but will still have the same set nonetheless.

so what I want to do is combine them into this:

heroList  = ['name','age','address','number'],['Peter Parker','16','Queens','123456789'];

So I've tried combining them using concat() method and it was producing the wrong output so Im wondering how I should format them to combine to my desired output.

Upvotes: 0

Views: 61

Answers (5)

Alfred M.
Alfred M.

Reputation: 189

You're right the example is syntactically wrong so In a hierarchy order i will just accept the first persons answer.Thanks

Upvotes: 0

user7951676
user7951676

Reputation: 367

You could use a multi dimensional array:

heroList = [[ 'name' , 'age' , 'address' , 'number' ],[ 'Peter Parker' , '16' , 'Queens' , '123456789' ]]; 

You can make this from a single dimensional array like:

arr1 = [ 'name' , 'age' , 'address' , 'number' ]
arr2=[ 'Peter Parker' , '16' , 'Queens' , '123456789' ]; 
newArr=[arr1,arr2]

Upvotes: 1

Max
Max

Reputation: 1556

as mentioned in the comments your notation for heroList is syntactically wrong, but I am guessing you mean: heroList = [['name','age','address','number'],['Peter Parker','16','Queens','123456789']]; ?

Maybe something like this:

oldArray = ['name','age','address','number'];
firstArray = ['Peter Parker','16','Queens','123456789'];

var heroList = [
  oldArray,
  firstArray
];

Upvotes: 3

YCotov
YCotov

Reputation: 92

You can try this one:

var heroList = (firstArray.join(",") + "," + oldArray.join(",")).split(",")

Upvotes: 0

andreybleme
andreybleme

Reputation: 689

By reading you expected output, the heroList should be an object, with the two arrays as attribute. Try this:

var oldArray = ['name','age','address','number'];

var firstArray = ['Peter Parker','16','Queens','123456789'];

var heroList = [];

heroList.push(oldArray);
heroList.push(firstArray);

Upvotes: 1

Related Questions