Reputation: 1870
Simply what I need to do is:
var a = [[[]]];
a[1][2][3] = "hello!"; // [...[undefined,undefined,undefined,"hello!"]...];
a[1][2][1] = "a"; // [...[undefined,"a",undefined,"hello!"]...]
a[2][3][4] = "new_index" // [...[undefined,"a",undefined,"hello!"]...[undefinedx4, "new_index"]]
In my case i prefer not to instantiate the size of array until the index is specified and increase the size when is required by larger index. What is the easiest or cleanest way to do it in javascript since js is weak supporting multi dimentional array?
Upvotes: 2
Views: 101
Reputation: 26161
In JS arrays are reference types so creating an ND array is tricky. A cloninig tool would be very handy. Accordingly you may do as follows;
Array.prototype.clone = function(){
return this.map(e => Array.isArray(e) ? e.clone() : e);
};
function arrayND(...n){
return n.reduceRight((p,c) => c = (new Array(c)).fill().map(e => Array.isArray(p) ? p.clone() : p ));
}
var arr = arrayND (2,3,4,"x")
console.log(JSON.stringify(arr));
The initial arguments define the dimensions and the very last argument is the fill value.
And this should work fine with pre ES6 compatible browsers;
Array.prototype.clone = function(){
return this.map(function(e){
return Array.isArray(e) ? e.clone() : e;
});
};
function arrayND(){
var n = Array.prototype.slice.call(arguments);
return n.reduceRight(function(p,c){
return c = Array(c).fill().map(function(e){
return Array.isArray(p) ? p.clone() : p;
});
});
}
var arr = arrayND (2,3,4,"x");
console.log(JSON.stringify(arr));
Upvotes: 1
Reputation: 718
Here is my solution:
function assign(input) {
if ('object' !== typeof input) {
let tmp = {};
tmp[input] = arguments[1];
input = tmp;
}
let regex = /\.?([^.\[\]]+)|\[(\d+)]/g;
let result = {};
for (let p in input) {
let data = result, prop = '', match;
while (match = regex.exec(p)) {
data = data[prop] || (data[prop] = (match[2] ? [] : {}));
prop = match[2] || match[1];
}
data[prop] = input[p];
}
return result[''];
}
// Example usage
let a = assign('3[4][5]', 'hello');
let b = assign('3[4][5][6]', 'world!');
let c = assign('you.can.use.object.as.well', 'cool!');
let d = assign('or.mix[3].them[2]', 'together!');
let e = assign({'with.multiple': 'properties', 'in.a.single': 'object'});
let f = assign({
'[1][2][3]': "hello!",
'[1][2][1]': "a",
'[2][3][4]': "new_index"
});
console.log(a[3][4][5], '->', JSON.stringify(a));
console.log(b[3][4][5][6], '->', JSON.stringify(b));
console.log(c.you.can.use.object.as.well, '->', JSON.stringify(c));
console.log(d.or.mix[3].them[2], '->', JSON.stringify(d));
console.log(e.with.multiple, '->', e.in.a.single, '->', JSON.stringify(e));
console.log('f[1][2][3]:', f[1][2][3]);
console.log('f[1][2][1]:', f[1][2][1]);
console.log('f[2][3][4]:', f[2][3][4]);
Upvotes: 1