'Rendering multiple boxes only displays correctly if perfectly squared

I'm using some logic to add boxes to my scene, based on how many items in height, width and depth, and that works well when they are all perfectly squared.

enter image description here

The problem comes if I want to use a different rectangular form:

enter image description here

I am quite a beginner at this. How can I correct it?

private addCubes() {
     // geometry
 const geometry = new THREE.BoxGeometry(1,4,4);
 const edgesGeometry = new THREE.EdgesGeometry(geometry);

 // material
 const material = new THREE.MeshBasicMaterial({
   color: 0x0d6efd,
 });
 const edgesMaterial = new THREE.LineBasicMaterial({
   color: 0x000000
 });

  // positions
for (let x = 0; x < 2; x++) {
  for (let y = 0; y < 1; y++) {
    for (let z = 0; z < 2; z++) {
      // mesh
      const mesh = new THREE.Mesh(geometry, material);
      mesh.scale.multiplyScalar(0.9);
      mesh.position.set(x, y, z);
      this.scene.add(mesh);

      const lines = new THREE.LineSegments(edgesGeometry, edgesMaterial);
      mesh.add(lines);
    }
  }
}
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source