Reputation: 276
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.
Upvotes: 0
Views: 276
Reputation: 138267
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));
Upvotes: 0
Reputation: 6994
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);
Upvotes: 1
Reputation: 584
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]];
}
}
Upvotes: 1