skip to Main Content

I am modifying the nested list and adding to an array now when I modify nested list it behaving very strangely, I am missing something very small but don’t know what.

class Square {
  constructor() {
    this.value = null;
    this.next = null;
  }
}

let square = new Square();
square.value = [0, 0];

let arrayOfValues = [[1,2], [2, 3], [4, 5]];
let resultArray = [];
arrayOfValues.forEach(v => {
  let copy = square;
  while (copy.next !== null) {
    copy = copy.next;
  }
  let nextNode = new Square()
  nextNode.value = v;
  copy.next = nextNode;
  resultArray.push(square);
})

console.log(resultArray) //[{value: [0, 0], next: {value: [1, 2], next: {value: [2, 3], next: {value: [4, 5], next: null}}}},....]


// want to return [{value: [0, 0], next: {value: [1, 2], next: null}}, ....]

2

Answers


  1. Use this corrected version:

    class Square {
          constructor() {
            this.value = null;
            this.next = null;
          }
        }
        
        let arrayOfValues = [[1,2], [2, 3], [4, 5]];
        let resultArray = [];
        
        arrayOfValues.forEach(v => {
          let newSquare = new Square();
          newSquare.value = [0, 0];
          
          let nextNode = new Square();
          nextNode.value = v;
          newSquare.next = nextNode;
          
          resultArray.push(JSON.parse(JSON.stringify(newSquare)));
        });
        
        console.log(resultArray);
    
    Login or Signup to reply.
  2. The problem is in this line:

    let copy = sqaure
    

    Objects (and inherently arrays) are passed reference in Javascript, so after this line copy and square are both pointing to the same object.

    to create a copy you need to initiate a new instance and copy the values. you can create a copy method in the class or simply create a new instance.

    class Square {
      constructor(value = null, next = null) {
        this.value = value
        this.next = next
      }
    
      clone() {
        return new Square(this.value, this.next)
      }
    }
    
    let square = new Square([0, 0])
    
    let arrayOfValues = [[1,2], [2, 3], [4, 5]]
    let resultArray = []
    
    arrayOfValues.forEach(v => {
      let current = square.clone()
      let nextNode = new Square(v)
      square.value = v
    
      current.next = nextNode
      resultArray.push(current)
    })
    console.log(resultArray)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search