按值使用 Typescript 对对象数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48195456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Order array of objects with Typescript by value
提问by Novo
How can I oder this array of Objects by Object value? Im using Typescript
如何按对象值对这个对象数组进行排序?我使用打字稿
console.log(this.items);
控制台日志(this.items);
(6) [{…}, {…}, {…}, {…}, {…}, {…}]
{id: 3, ref: "P-201721", active: 1, visible: 1, weigth: 0.3,?…}
{id: 4, ref: "P-201722", active: 1, visible: 1, weigth: 0.3,?…}
{id: 1, ref: "P-201710", active: 1, visible: 1, weigth: 0.5,?…}
{id: 2, ref: "P-201711", active: 1, visible: 1, weigth: 0.5,?…}
{id: 5, ref: "P-201831", active: 1, visible: 1, weigth: 0.2,?…}
{id: 6, ref: "P-201832", active: 1, visible: 1, weigth: 0.2,?…}
I tried this but the array mantains the same order Sort an array with arrays in it by string
我试过这个,但数组保持相同的顺序 按字符串对包含数组的数组进行排序
回答by fl0psy
Sorting an array of objects can be a little tricky. You have to pass in a custom sorting function to define how you want to compare the objects. How else would .sort() know you want to sort by id? Maybe you want to sort by weight instead.
对一组对象进行排序可能有点棘手。您必须传入自定义排序函数来定义要如何比较对象。.sort() 怎么知道你想按 id 排序?也许您想按重量排序。
I've put together an example at https://codepen.io/anon/pen/PEReGE?editors=0012. You can replace the id references with any property if you'd like it sorted by that instead.
我在https://codepen.io/anon/pen/PEReGE?editors=0012整理了一个例子。如果您希望按此排序,您可以将 id 引用替换为任何属性。
items.sort((a, b) => {
if(a.id > b.id) {
return 1;
} else if(a.id < b.id) {
return -1;
} else {
return 0;
}
});
If you are sorting by a numeric property you can use this shorthand:
如果您按数字属性排序,则可以使用以下简写:
items.sort((a, b) => {
return a.id - b.id;
});
回答by a2441918
You can use lodash to achieve what you want. You can also use multiple sorting options by passing in the keys in the array inside the sortBy function.
你可以使用 lodash 来实现你想要的。您还可以通过在 sortBy 函数内传入数组中的键来使用多个排序选项。
var data = [
{"id": 3, "ref": "P-201721", "active": 1, "visible": 1, "weight": 0.3},
{"id": 4, "ref": "P-201722", "active": 1, "visible": 1, "weight": 0.3},
{"id": 1, "ref": "P-201710", "active": 1, "visible": 1, "weight": 0.5},
{"id": 2, "ref": "P-201711", "active": 1, "visible": 1, "weight": 0.5},
{"id": 5, "ref": "P-201831", "active": 1, "visible": 1, "weight": 0.2},
{"id": 6, "ref": "P-201832", "active": 1, "visible": 1, "weight": 0.2}
]
var sort = _.sortBy(data, ["id","weight"]);
console.log(sort);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>