【问题标题】:Sort an array of objects in typescript?在打字稿中对一组对象进行排序?
【发布时间】:2017-04-09 19:44:51
【问题描述】:

如何在 TypeScript 中对对象数组进行排序?

具体来说,根据一个特定属性对数组对象进行排序,在本例中为nome(“姓名”)或cognome(“姓氏”)?

/* Object Class*/
export class Test{
     nome:String;
     cognome:String;
}

/* Generic Component.ts*/
tests:Test[];
test1:Test;
test2:Test;

this.test1.nome='Andrea';
this.test2.nome='Marizo';
this.test1.cognome='Rossi';
this.test2.cognome='Verdi';

this.tests.push(this.test2);
this.tests.push(this.test1);

谢谢!

【问题讨论】:

  • 你试过什么?请显示您尝试过的代码,我们可以建议如何修复它。

标签: angular sorting typescript


【解决方案1】:

这取决于您要排序的内容。您可以在 JavaScript 中为 Array 提供标准的 sort 功能,并且可以为对象编写专门的复杂条件。 f.e

var sortedArray: Test[] = unsortedArray.sort((obj1, obj2) => {
    if (obj1.cognome > obj2.cognome) {
        return 1;
    }

    if (obj1.cognome < obj2.cognome) {
        return -1;
    }

    return 0;
});

【讨论】:

  • 这只是一个小例子,我的数组由不少于20个元素组成
  • 我猜你不理解作为排序方法参数传递的函数。该函数始终有两个参数(数组中的对象类型相同),它显示了如何对数组进行排序。在我的示例中,数组的大小无关紧要。数组可能有两个或一千个元素。排序将通过函数的比较元素 (obj1, obj2) => { //..comparing } 每次
  • 你也可以使用localeCompare代替多个if:(obj1, obj2) =&gt; obj1.cognome.localeCompare(obj2.cognome)
【解决方案2】:

对我来说最简单的方法是:

升序:

arrayOfObjects.sort((a, b) => (a.propertyToSortBy < b.propertyToSortBy ? -1 : 1));

降序:

arrayOfObjects.sort((a, b) => (a.propertyToSortBy > b.propertyToSortBy ? -1 : 1));

在你的情况下, 升序:

testsSortedByNome = tests.sort((a, b) => (a.nome < b.nome ? -1 : 1));
testsSortedByCognome = tests.sort((a, b) => (a.cognome < b.cognome ? -1 : 1));

降序:

testsSortedByNome = tests.sort((a, b) => (a.nome > b.nome ? -1 : 1));
testsSortedByCognome = tests.sort((a, b) => (a.cognome > b.cognome ? -1 : 1));

【讨论】:

  • 您好,我们可以在指定参数名称的同时使用参数吗?就像你做了 a.name 一样,我们可以做 a.(some parameter which has the prop name)吗?
【解决方案3】:
    const sorted = unsortedArray.sort((t1, t2) => {
      const name1 = t1.name.toLowerCase();
      const name2 = t2.name.toLowerCase();
      if (name1 > name2) { return 1; }
      if (name1 < name2) { return -1; }
      return 0;
    });

【讨论】:

    【解决方案4】:
    this.tests.sort(t1,t2)=>(t1:Test,t2:Test) => {
        if (t1.nome > t2.nome) {
            return 1;
        }
    
        if (t1.nome < t2.nome) {
            return -1;
        }
    
        return 0;
    }
    

    你试过这样的吗?

    【讨论】:

    • 如何实现像我的数组大小周期性变化一样通用的东西?
    • 它对所有列表进行排序,如果列表大小发生变化,排序后的数组大小也会发生变化
    【解决方案5】:
    [{nome:'abc'}, {nome:'stu'}, {nome:'cde'}].sort(function(a, b) {
      if (a.nome < b.nome)
        return -1;
      if (a.nome > b.nome)
        return 1;
      return 0;
    });
    

    【讨论】:

      【解决方案6】:

      你可以使用这个方法。

      let sortedArray: Array<ModelItem>;
      sortedArray = unsortedArray.slice(0);
      sortedArray.sort((left, right) => {
          if (left.id < right.id) return -1;
          if (left.id > right.id) return 1;
          return 0;
      })
      

      【讨论】:

        【解决方案7】:

        您可以使用具有泛型类型的函数:

        const sortArrayOfObjects = <T>(
          data: T[],
          keyToSort: keyof T,
          direction: 'ascending' | 'descending' | 'none',
        ) => {
          if (direction === 'none') {
            return data
          }
          const compare = (objectA: T, objectB: T) => {
            const valueA = objectA[keyToSort]
            const valueB = objectB[keyToSort]
        
            if (valueA === valueB) {
              return 0
            }
        
            if (valueA > valueB) {
              return direction === 'ascending' ? 1 : -1
            } else {
              return direction === 'ascending' ? -1 : 1
            }
          }
        
          return data.slice().sort(compare)
        }
        

        现在如果您使用该函数对对象数组进行排序,您可以指定要排序的对象属性。

        const array = [
          { id: 2, name: "name2" },
          { id: 1, name: "name1" },
          { id: 3, name: "name3" }
        ];
        
        const sortedArray = sortArrayOfObjects(array, "id", "ascending")
        
        console.log(sortedArray)
        //sorted ascending by id
        // [
        //   { id: 1, name: "name1" },
        //   { id: 2, name: "name2" },
        //   { id: 3, name: "name3" }
        // ]
        

        使用泛型类型和“keyOf T”作为属性类型有助于我们仅选择可用的对象属性,在本例中为“id”和“name”。 typescript helper

        CodeSandbox example

        【讨论】:

          【解决方案8】:

          我正在使用 angular 7,我尝试了 pipe,但没有成功,我尝试了这个并得到了正确的输出。

          让对象数组在对象结果中

          results:any ={
           "providers": [
            {
              "name": "AAA",
              "error": {
                "success": true,
                "message": "completed"
              },
              "quote_id": "BA503452VPC0012790",
              "quotes": {
                "comprehensive": {
                  "premiumBreakup": {
                    "premium": "17398.0",
                  }
                },
              }
            },
            {
              "name": "Fi",
          
              "error": {
                "success": true,
                "message": "completed"
              },
              "quotes": {
                "comprehensive": {
                  "premiumBreakup": {
                    "premium": "27957.00"              
                  }
                },
              }
            },
          ]
          }
          

          点击排序功能

          <button class="t-sort-optn" (click)="sortByPremium()">Premium</button>
          

          按溢价排序

          sortByPremium(){
              var items = this.results.providers;
              console.log("Array",items);
              items.sort(function (a, b) {
              return a.quotes.comprehensive.premiumBreakup.premium - b.quotes.comprehensive.premiumBreakup.premium;
              });
              console.log("Array Sorted",items)
          }
          

          【讨论】:

            【解决方案9】:

            这对我来说是这样的

            .sort((a, b) => {
              const a2 = a as unknown as Type;
              const b2 = b as unknown as Type;
              if (a2.something > b2.something) {
                return 1;
              }
              
              if (a2.something < b2.something) {
                return -1;
              } 
            
              return 0;
            })
            

            【讨论】:

              【解决方案10】:

              我经常需要对数据集结果中的单个字段进行排序,比如Id,最短的写法就是这样

              data.sort((a, b) => a.Id - b.Id)
                  .forEach(row => {
                         //something with row
                   });
              

              【讨论】:

                【解决方案11】:

                将您的数组视为 myArray,

                myArray.sort(( a, b ) => a > b ? 1 : 0 )
                

                【讨论】:

                • 这应该是myArray.sort(( a, b ) =&gt; a &gt; b ? 1 : -1 )
                猜你喜欢
                • 2018-10-09
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2017-03-19
                • 2020-08-04
                • 2017-02-12
                • 1970-01-01
                • 2022-11-25
                相关资源
                最近更新 更多