skip to Main Content

I used a class to class to organize everything I needed in this small project and made it require a 2d array to print out a field to the screen

class Field {
  constructor(fieldArr) {
    this.fieldArr = fieldArr;
  }
  get field() {
    return this.print(); 
  }
  print() {
    console.log(this.fieldArr.join("n")) // new line made after each array
  }
}

const myField = new Field([
    ["*", "░", "O"],
    ["░", "░", "░"],
    ["O", "░", "O"]
])
myField.print()

expected:

*░O
░░░
O░O

got:

*,░,O
░,░,░
O,░,O

3

Answers


  1. You are working with a 2-d array, but you join() the outer array.

    YOu should map() each inner item, to join() those (with nothing for now), and then join() the resulting string with a newlinE:

    class Field {
      constructor(fieldArr) {
        this.fieldArr = fieldArr;
      }
      get field() {
        return this.print(); 
      }
      print() {
        console.log(this.fieldArr.map(m => m.join("")).join("n")) // new line made after each array
      }
    }
    
    const myField = new Field([
        ["*", "░", "O"],
        ["░", "░", "░"],
        ["O", "░", "O"]
    ])
    myField.print()
    Login or Signup to reply.
  2. I think, the print() method is logging each element of the arrays individually instead of joining them together.
    
    class Field {
        constructor(fieldArr) {
          this.fieldArr = fieldArr;
        }
        
        get field() {
          return this.print();
        }
        
        print() {
          for (let row of this.fieldArr) {
            console.log(row.join("")); // concatenate elements before joining
          }
        }
      }
      
      const myField = new Field([
          ["*", "░", "O"],
          ["░", "░", "░"],
          ["O", "░", "O"]
      ]);
      
      myField.print();
    
    
    Now expected result.
    
    *░O
    ░░░
    O░O
    Login or Signup to reply.
  3. You are working with a multidimensional array… to manipulate data you have to step twice to reach the inner array but the way your code is written it only works on the outer array.

    I’ve made an edit to your code to make it work but this is for only manipulating the commas.

    class Field {
      constructor(fieldArr) {
        this.fieldArr = fieldArr;
      }
      get field() {
        return this.print(); 
      }
      print() {
        console.log(this.fieldArr.join("n").replace(/,/g,"")) // new line made after each array
      }
    }
    
    const myField = new Field([
        ["*", "░", "O"],
        ["░", "░", "░"],
        ["O", "░", "O"]
    ])
    myField.print()
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search