Javascript根据数字键对对象数组进行排序

问题描述:

我有一个看起来像这样的对象数组:

I have an array of objects that looks like this:

var data = [
 {
   title: 'Shirt',
   position: 3
 },
 {
   title: 'Ball',
   position: 1,
 }
]

我该如何对它进行排序以便在 for循环中使用.

How could I sort it for use in a for loop like this.

for(var i in data) {

}

我尝试过:

for(数据中的变量i | orderBy:'position')

但这是有角度的,因此普通的Javascript无法正常工作.

But that is angular so normal Javascript it doesn't work.

我认为他们必须采用某种方法在遍历数组之前对数组进行排序,或者在循环中添加过滤器,不确定哪种方法是最好的.

I'm thinking their must be some way to sort the array before looping through it, or adding a filter to the loop, not sure which is the best way.

但这是有角度的,因此普通的Javascript无法正常工作.

But that is angular so normal Javascript it doesn't work.

您只需使用JavaScript sort 一个>功能.它也将在Angular(TypeScript)中工作.

Simply you can use JavaScript sort function. It will work in Angular(TypeScript) also.

注意::对数字进行排序时,只需使用紧凑比较:

Note: When sorting numbers, you can simply use the compact comparison:

myArray.sort((n1,n2)=> n1-n2);

var data = [
 {
   title: 'Shirt',
   position: 3
 },
 {
   title: 'Ball',
   position: 1,
 }
];

 data.sort(function(a, b) { 
return a.position- b.position;
})

console.log(data);