Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to join a two-dimensional array in Javascript

I'm trying to convert a two-dimensional array to a string in order to store it in the localStorage array. However, there is something wrong with this code I cannot identify:

for(x in array) {
    if(array[x] instanceof Array) {
        array[x] = array[x].join("`");
    }
}
var string = array.join("@");
localStorage[key] = string;

Does anyone have an idea what I'm doing wrong?

As for what's wrong, by multidimensional array I mean array[0][1] etc. When input into localStorage, all the 'string' is reduced to is @, implying on the other side of the @ there are still arrays.

like image 991
Arda Xi Avatar asked Jan 06 '10 20:01

Arda Xi


People also ask

How do you access an array inside an array?

To access an element of the multidimensional array, you first use square brackets to access an element of the outer array that returns an inner array; and then use another square bracket to access the element of the inner array.

Does JavaScript support multi dimensional array?

Javascript has no inbuilt support for multidimensional arrays, however the language is flexible enough that you can emulate this behaviour easily by populating your arrays with separate arrays, creating a multi-level structure.


1 Answers

Nowadays this is as simple as:

[[1,2],[3,4]].map(e => e.join(':')).join(';'); // 1:2;3:4
like image 157
Jonatas Walker Avatar answered Sep 19 '22 14:09

Jonatas Walker