qwang07
qwang07

Reputation: 1256

JavaScript - What's the error in the recursive function?

I try to get the whole path of a query id. For example, getPath(6, rawData) should return [1,2,6]. However, it returns [6,6,6]. When I try console.log inside the code, it looks like the value of the node inside the self-called function will overwrite the value of the node outside. I cannot figure out what's wrong with the recursive function. Or somebody can teach me a new way to achieve the same goal?

Here is the code:

const getPath = (id, list) => {
  if (!list || !Array.isArray(list)) {
    return false
  }

  for (node of list) {
    if (node.id === id) {
      return [node.id]
    }

    let res = getPath(id, node.children)

    if (res) {
      return [node.id, ...res]
    }
  }

  return false
}

const rawData = [{
    id: 1,
    parent: null,
    children: [{
      id: 2,
      parent: 1,
      children: [{
        id: 4,
        parent: 2,
        children: null
      }, {
        id: 5,
        parent: 2,
        children: null
      }, {
        id: 6,
        parent: 2,
        children: null
      }]
    }]
  },
  {
    id: 3,
    parent: null,
    children: [{
        id: 7,
        parent: 3,
        children: [{
          id: 9,
          parent: 7,
        }]
      },
      {
        id: 8,
        parent: 3,
      }
    ]
  }
]

console.log(getPath(2, rawData))

Upvotes: 1

Views: 209

Answers (1)

Barmar
Barmar

Reputation: 780744

You need to declare the variable node so it's local to the function.

const getPath = (id, list) => {
  if (!list || !Array.isArray(list)) {
    return false
  }

  for (let node of list) {
    if (node.id === id) {
      return [node.id]
    }

    let res = getPath(id, node.children)

    if (res) {
      return [node.id, ...res]
    }
  }

  return false
}

const rawData = [{
    id: 1,
    parent: null,
    children: [{
      id: 2,
      parent: 1,
      children: [{
        id: 4,
        parent: 2,
        children: null
      }, {
        id: 5,
        parent: 2,
        children: null
      }, {
        id: 6,
        parent: 2,
        children: null
      }]
    }]
  },
  {
    id: 3,
    parent: null,
    children: [{
        id: 7,
        parent: 3,
        children: [{
          id: 9,
          parent: 7,
        }]
      },
      {
        id: 8,
        parent: 3,
      }
    ]
  }
]

console.log(getPath(2, rawData))

Upvotes: 5

Related Questions