【问题标题】:How to sort an array of objects by comparing different fields in typescript如何通过比较打字稿中的不同字段对对象数组进行排序
【发布时间】:2021-10-23 10:04:57
【问题描述】:

所以我找到了有关如何通过比较相同字段对数组进行排序的示例,但我需要通过比较不同字段对它们进行排序。例如,我有一个对象列表,其中每个对象都有一个字段作为其名称和父级。我想对列表进行排序,以便人们出现在他们的父母旁边。示例:

[
  {
    "name": "Bob",
    "parent": "Linda"
  },
  {
    "name": "Charlie",
    "parent": "Gregory"
  },
  {
    "name": "Linda",
    "parent": "Stacy"
  },
  {
    "name": "Andrew",
    "parent": "Gabriel"
  },
  {
    "name": "Gregory",
    "parent": "Thomas"
  }
]

排序后,我希望 Bob 在 Linda 旁边,Charlie 在 Gregory 旁边。

【问题讨论】:

    标签: javascript arrays typescript sorting object


    【解决方案1】:

    你好@poppo8989:欢迎来到 Stack Overflow。

    建议:如果您可以控制问题中呈现的数据,则可以考虑将其存储在更能代表关系的结构中。

    否则,以下是解决您问题的方法:

    Explore code in TypeScript Playground

    type Person = {
      name: string;
      parent: string;
    };
    
    type RelationshipData = {
      child?: Person;
      parent?: Person;
    };
    
    function getRelationships (people: Person[], person: Person): RelationshipData {
      return {
        child: people.find(p => p.parent === person.name),
        parent: people.find(p => p.name === person.parent),
      };
    }
    
    function getSortedPeople (people: Person[]): Person[] {
      const sorted: Person[] = [];
      const copy = [...people];
    
      while (copy.length > 0) {
        let person: Person | undefined = copy[0];
        let done = false;
    
        // set person to furthest ancestor
        while (person && !done) {
          const {parent} = getRelationships(copy, person);
          if (parent) person = parent;
          else done = true;
        }
    
        // remove from copy array and add to sorted array, repeatedly for each child
        while (person) {
          copy.splice(copy.indexOf(person), 1);
          sorted.push(person);
          person = getRelationships(copy, person).child;
        }
      }
    
      return sorted;
    }
    
    function main () {
      const people: Person[] = [
        {name: 'Bob', parent: 'Linda'},
        {name: 'Charlie', parent: 'Gregory'},
        {name: 'Linda', parent: 'Stacy'},
        {name: 'Andrew', parent: 'Gabriel'},
        {name: 'Gregory', parent: 'Thomas'},
      ];
    
      const sorted = getSortedPeople(people);
      console.log(sorted); //=> Linda, Bob, Gregory, Charlie, Andrew
    }
    
    main();
    

    【讨论】:

      猜你喜欢
      • 2018-10-09
      • 2017-03-19
      • 2019-02-02
      • 1970-01-01
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      相关资源
      最近更新 更多