EN
JavaScript - create multidimensional array
6
points
In this article, we would like to show you how to create a multidimensional array using JavaScript.
Practical example
Function that creates multidimensional array should use recurrence to be universal.
The below function takes 3 arguments:
dimensions- it lets to configure multidimensional array size,creator- method that creates array items (by default array is filled usinghnullvalues),indexes- auxiliary argument in which currnet creation indexes are stored (e.g. it lets to create fragment of another array).
// ONLINE-RUNNER:browser;
const createArray = (dimmensions, creator = (...indexes) => null, indexes = []) => {
if (indexes.length < dimmensions.length) {
const array = Array(dimmensions[indexes.length]);
for (let i = 0; i < array.length; ++i) {
indexes.push(i);
array[i] = createArray(dimmensions, creator, indexes);
indexes.pop();
}
return array;
}
return creator(...indexes);
};
// Usage example:
const array1 = createArray([3], (index) => `item-${index}`);
const array2 = createArray([3, 2], (index1, index2) => `item-${index1}-${index2}`);
const array3 = createArray([3, 2, 1], (index1, index2, index3) => `item-${index1}-${index2}-${index3}`);
console.log(JSON.stringify(array1));
console.log(JSON.stringify(array2));
console.log(JSON.stringify(array3));