Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an empty two dimensional array in Javascript, with keys

I'm trying to create a matrix in Javascript, but one which has predefined keys for the X and Y axis.

For example I have the following keys

const x = [2,4,6,8]
const y = [10,20,40,60,80]

I found the following snippet which creates an empty two dimensional array with 4 rows and 5 columns

[...Array(4)].map(x=>Array(5).fill(0))       

I'm wondering if it's possible to create these arrays (objects), but using provided keys to go with it.

So the end result would look like this.

{
    2 => {10 => 0, 20 => 0, 40 => 0, 60 => 0, 80 => 0}
    4 => {10 => 0, 20 => 0, 40 => 0, 60 => 0, 80 => 0}
    6 => {10 => 0, 20 => 0, 40 => 0, 60 => 0, 80 => 0}
    8 => {10 => 0, 20 => 0, 40 => 0, 60 => 0, 80 => 0}
}
like image 277
Miguel Stevens Avatar asked Nov 14 '19 10:11

Miguel Stevens


People also ask

How do you create an array of two-dimensional?

To create an array use the new keyword, followed by a space, then the type, and then the number of rows in square brackets followed by the number of columns in square brackets, like this new int[numRows][numCols] . The number of elements in a 2D array is the number of rows times the number of columns.


1 Answers

You could create the wanted objects by looping and reducing the data.

The callback of Array#reduce takes as first parameter the accumulator, here it is an object, and as second parameter the value of the iterating array.

As startValue for the reduce, it take an (kind of empty) object and usdes this object to add properties. To have this object (aka accumulator) ready for the next loop (and final result), it has to be returned.

var x = [2, 4, 6, 8],
    y = [10, 20, 40, 60, 80],
    result = x.reduce((r, k) => {
        r[k] = y.reduce((q, l) => {
            q[l] = 0;
            return q;
        }, {});
        return r;
    }, {});

console.log(result);
like image 101
Nina Scholz Avatar answered Nov 06 '22 01:11

Nina Scholz