简体   繁体   中英

Create 2d array from edges arrays

I have input:

const topMatrix = [ 1, 2, 3, 4 ] ;
const leftMatrix = [ 0, 5, 10 ] ;
const rightMatrix = [ 9, 14, 19 ] ;
const bottomMatrix = [ 15, 16, 17, 18 ];

and from above arrays I want to create array like this:

[
    [1, 2, 3, 4, 9],
    [0, empty, empty, empty, 14],
    [5, empty, empty, empty, 19],
    [10, 15, 16, 17, 18]
]

So top and bottom are almost same.

Then left column I just need to unshift from 1 to last one (excluding 0).

Then right column I just need to push from 0 to last one - 1 (excluding last).

What I've done so far is:

const topMatrix = [ 1, 2, 3, 4 ] ;
const leftMatrix = [ 0, 5, 10 ] ;
const rightMatrix = [ 9, 14, 19 ] ;
const bottomMatrix = [ 15, 16, 17, 18 ];

const combineEdges = (top, left, right, bottom) => {
  const newArray = new Array(4);
  newArray.fill(new Array(4))

  //fill top and bottom
  newArray[0] = top;
  newArray[newArray.length - 1] = bottom;

  //fill left
  for(let i = 0, l = left.length; i < l; i++) {
    if(newArray[i + 1]) {
      newArray[i + 1].unshift(left[i]);
    }
  }

  //fill right
  for(let i = 0, l = right.length; i < l; i++) {
    if(newArray[i]) {
      newArray[i].push(right[i]);
    }
  }

  return newArray;
}

console.log(
  combineEdges(topMatrix, leftMatrix, rightMatrix, bottomMatrix)
)

And now I have problem because I create array "dummy" by .fill and this cause that its behaviour is odd to me. For example this fill left loop is unshifting elements and duplicating 5 for some reason which I completly don't understand.

Currently output is:

0: (5) [1, 2, 3, 4, 9]
1: (8) [5, 0, empty × 4, 14, 19]
2: (8) [5, 0, empty × 4, 14, 19]
3: (5) [10, 15, 16, 17, 18]

I have no clue why there's doubled 5 in 1 and 2 and doubled 19 apparently I'm doing something wrong. I think problem lays in way which I'm creating new array.

Can someone explain what's happening here?

According to the documentation Array.fill() fills your array with a static component. Meaning you fill your Array 4 times with the same array. Then you override it in postion 0 & 3 but not 1 & 2.

Since this is the same array at position 1 & 2, you add the same numbers to both arrays.

You want to remove

newArray.fill(new Array(4))

and instead fill it manually

  //fill top and bottom
  newArray[0] = top;
  newArray[1] = new Array(3);
  newArray[2] = new Array(3);
  newArray[newArray.length - 1] = bottom;

I also adjusted it to new Array(3) because in your example you wanted 3 empty entries in the middle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM