Languages
[Edit]
EN

JavaScript - create multidimensional array

6 points
Created by:
Zayyan-Todd
860

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 usingh null values),
  • 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));

 

References

  1. Array.prototype.push() - JavaScript | MDN
  2. Array.prototype.pop() - JavaScript | MDN
  3. Spread syntax (...) - JavaScript | MDN

Alternative titles

  1. JavaScript - create multi dimensional array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join