在打字稿中对对象数组进行排序?

时间:2017-04-09 19:44:52

标签: angular sorting typescript

如何在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);

THX!

10 个答案:

答案 0 :(得分:24)

这取决于您想要排序的内容。您在JavaScript中具有 Array 的标准排序功能,您可以编写专用于对象的复杂条件。 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;
});

答案 1 :(得分:13)

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

升序:

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));

答案 2 :(得分:5)

    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;
    });

答案 3 :(得分: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;
}
你试过这样的吗?

答案 4 :(得分:2)

playground

答案 5 :(得分:2)

您可以使用此方法。

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;
})

答案 6 :(得分:0)

将您的数组视为myArray,

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

答案 7 :(得分:0)

我使用的是Angle 7,我尝试了管道,但是没有用,我尝试了一下,并获得了正确的输出。

让对象数组出现在对象结果中

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)
}

答案 8 :(得分:0)

这就是我的工作方式

.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;
})

答案 9 :(得分:0)

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

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

相关问题