首页 > 解决方案 > 需要帮助编写一个递归函数来查找一个人的后代。JavaScript

问题描述

我正在尝试编写一个函数来查找一个人的后代。我拥有的数据设置在一个数组中,格式如下:

    {
        "id": 159819275,
        "firstName": "Jasmine",
        "lastName": "Bob",
        "gender": "female",
        "dob": "12/18/1969",
        "height": 58,
        "weight": 156,
        "eyeColor": "blue",
        "occupation": "assistant",
        "parents": [409574486, 260451248],
        "currentSpouse": 951747547
    },

我编写的函数接受我正在寻找其后代的人的 ID、人员数组,并创建一个包含后代的新数组。

function findDescendants (id, people, descendantsArray = []){

 descendantsArray = people.filter(function(el){
      return el.parents[0] === id || el.parents[1 === id] //id works if it's a variable, but if it's a array it won't work. otherwise function is good 
    })    
  displayPeople(descendantsArray)  //calls a method that alerts the descendant's names into a string
  id = [];   //resets the id and turns it into an array
  for(let i = 0; i<descendantsArray.length; i++){
    id[i] = descendantsArray[i].id
  }           //puts the id's of the listed descendants into the array id

  if (descendantsArray.length === 0){
    return descendantsArray;
  } 
  else {
    findDescendants(id, people, descendantsArray)
  } //sends in the array id, the data set people, and the descendantsArray (which contains the children of the person in question. 
}

我的问题是,当我第二次调用数组时,过滤器不会将 el.parents 与 id 中的所有元素进行比较,我不知道从这里去哪里。

descendantsArray = people.filter(function(el){
      return el.parents[0] === id || el.parents[1 === id] //id works if it's a variable, but if it's a array it won't work. otherwise function is good 
    })  

我希望这个语句做的是过滤掉“父母:”包含id数组中的任何元素的人中的所有元素。任何帮助,将不胜感激。

标签: javascriptarraysrecursionfilterdataset

解决方案


你可以这样写:

const getDescendents = (people, id) =>
  people .filter (({parents = []}) => parents .includes (id))
         .flatMap (person => [person, ... getDescendents (people, person.id)])

如果我们有一棵这样的树:

                                 Alice + Bob    
                                       |
                       +---------------+--------------+
                       |                              |
           Charlie + Denise                        Edward + Francine    
                   |                                      |
            +------+-------+                              |
            |              |                              |
  Geroge + Helen         Irwin + Jean                 Kayleigh     
                               |         
                               |
                               |
                             Leroy 

并且我们调用getDescendents(people, 1)(其中 Alice 有 id 1),我们将取回代表这些人的对象:[Denise, Helen, Irwin, Leroy, Edward, Kayleigh]。这涉及数据的深度优先、前序遍历。如果我们想要排序(按 id 或其他),我们可以在调用之后进行排序,或者——在性能稍有下降的情况下——作为函数的最后一步:

const getDescendents = (people, id) =>
  people .filter (({parents = []}) => parents .includes (id))
         .flatMap (person => [person, ... getDescendents (people, person.id)])
         .sort (({id: a}, {id: b}) => a - b)


const people = [{name: 'Alice', id: 1, parents: []}, {name: 'Bob', id: 2, parents: []}, {name: 'Charlie', id: 3, parents: []}, {name: 'Denise', id: 4, parents: [1, 2]}, {name: 'Edward', id: 5, parents: [1, 2]}, {name: 'Francine', id: 6, parents: []}, {name: 'George', id: 7, parents: []}, {name: 'Helen', id: 8, parents: [3, 4]}, {name: 'Irwin', id: 9, parents: [3, 4]}, {name: 'Jean', id: 10, parents: []}, {name: 'Kayleigh', id: 11, parents: [5, 6]}, {name: 'Leroy', id: 12, parents: [9, 10]}]

people .forEach (
  ({name, id}) => console .log (
    `${name} ==> [${getDescendents(people, id).map(({name}) => name).join(', ')}]`
  )
)

console .log ('Denise\'s descendents: ', getDescendents (people, 4))
.as-console-wrapper {max-height: 100% !important; top: 0}


推荐阅读