0

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.

2
  • 1
    What you want to achieve is not possible because a variable can't be "two arrays" like that ... did you mean heroList = [['name','age','address','number'],['Peter Parker','16','Queens','123456789']]; - which is simply heroList = [oldArray, firstArray] Commented Jul 24, 2017 at 22:57
  • @JaromandaX this is exactly what I wanted to do thanks! I'll accept your answer since you're the first one :) Commented Jul 24, 2017 at 23:10

5 Answers 5

3

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
];
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

1

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]

Comments

0

You can try this one:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.