0

I have a 2D array that I get from a database. It looks like that:

arrayDB = [url1,name1,url2,name2,url3,name3, ...]

Now I want to save this array within my code. I tried:

function symbolsArray(syms){
    var tableArray = [];
    var tableArray2 = [];

    for (var i = 0; i < syms.length; i++) {
        tableArray[i] = syms[i][0]; //url
        tableArray2[i] = syms[i][1]; //Name
    }
}

However, this approach is not really suitable because I would need two return values. Is there maybe a better approach or a way to solve the content in a 2D array?

Syms is the data from the database.

2
  • 2
    Your arrayDB looks like a 1D array to me. Unless your array is made up of sub-arrays who have actual values then it's a 1D array. Also, is syms the data from the database? Why do you need to copy it into different arrays? Commented Jan 31, 2017 at 15:36
  • your code doesnt work or your arrayDB is wrong ( may [[url1,name1],[url2,name2]] ?) Commented Jan 31, 2017 at 15:37

3 Answers 3

1

Do take a look at How can I create a two dimensional array in JavaScript?

that answers similar question about 2d arrays in javascript. Try something like-

function symbolsArray(syms){
    var tableArray = [];

    for (var i = 0; i < syms.length; i++) {
        tableArray[i] = [syms[i][0] , syms[i][1]];
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I have seen it but wasn't able to adapt it to my code. Your approach seems to work for me.
1

Your array is not two dimensional.You can seperate urls and names like this...

arrayDB = ['url1','name1','url2','name2','url3','name3'];//assumed array
urls = [];//array for urls
names = [];//array for names
for(i=0;i<arrayDB.length;i++){
 (i%2==0)?urls.push(arrayDB[i]):names.push(arrayDB[i]);
}
console.log(names);
console.log(urls);

Comments

0

If ive got you right, your problem is that your code needs to return two things, but return does just one, right?

May Return an Object:

return {names: tableArray2,urls:tableArray};

You could use it like this:

var mydata=symbolsArray(arrayDB);
console.log(mydata.names,mydata.urls);

If you just want to deep clone, do:

var cloned=JSON.parse(JSON.stringify(arrayDB));

Or more elegantly:

var cloned=arrayDB.map(el=>el.map(e=>e));

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.