Javascript根据数字键对对象数组进行排序 [英] Javascript sort an array of objects based on numeric key

查看:55
本文介绍了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);

这篇关于Javascript根据数字键对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆