admin管理员组

文章数量:1393843

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}
}

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}
}
Share Improve this question edited Nov 18, 2019 at 17:58 Miguel Stevens asked Nov 14, 2019 at 10:02 Miguel StevensMiguel Stevens 9,24019 gold badges75 silver badges136 bronze badges 5
  • 2 why not take an object? – Nina Scholz Commented Nov 14, 2019 at 10:03
  • Well yes technically it would be an object since assoc array don't exist in js. I'll edit – Miguel Stevens Commented Nov 14, 2019 at 10:04
  • Instead of Array(5).fill(0) try Array.from( {length: 5}, () => 0 ) – Rajesh Commented Nov 14, 2019 at 10:07
  • Are you trying to create a sparse matrix? Apparently there are ready-made JS libraries to work with sparse matrices, e.g. math.js. – stop-cran Commented Nov 14, 2019 at 11:00
  • @stop-cran No it's just to try and create an editable grid as a form. – Miguel Stevens Commented Nov 14, 2019 at 12:17
Add a ment  | 

4 Answers 4

Reset to default 5

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);

You could map the y array to get the entries for a row object. Use Object.fromEntries() to get an object from the entries. Then map the x array to get the output object with a copy of each row object as value

const x = [2, 4, 6, 8],
      y = [10, 20, 40, 60, 80],
      row = Object.fromEntries( y.map(v => [v, 0]) ),
      output = Object.fromEntries( x.map(key => [key, { ...row }]) )

console.log(output)

Cloning is required because modifying one of the rows will update the other values since they are all pointing to the same reference

You can try following.

  • Since you have same object repeated as child object, create it first.
  • Now loop over parent keys and using spread or Object.assign, set it as object.

This way you have less number of iteration and code looks clean

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

const innerObj = y.reduce((acc, item) => {
  acc[ item ] = 0;
  return acc;
}, {});

const result = x.reduce((acc, item) => {
  acc[ item ] = { ...innerObj };
  return acc;
}, {});

console.log(result)

You could use forEach loop:

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

let results = {};
x.forEach(k => {
  let inner = {};
	
  y.forEach(v => inner[v] = 0);
  results[k] = inner;
});

console.log(results);

本文标签: Create an empty two dimensional array in Javascriptwith keysStack Overflow