Javascript基于数字键对对象数组进行排序(Javascript sort an array of objects based on numeric key)

编程入门 行业动态 更新时间:2024-10-24 14:23:31
Javascript基于数字键对对象数组进行排序(Javascript sort an array of objects based on numeric key)

我有一个对象数组,如下所示:

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

我怎么能把它排序在像这样的for loop使用。

for(var i in data) { }

我试过了:

for(var i in data | orderBy:'position')

但这是有角度的,所以正常Javascript它不起作用。

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

I have an array of objects that looks like this:

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

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

for(var i in data) { }

I tried:

for(var i in data | orderBy:'position')

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它不起作用。

您只需使用JavaScript 排序功能即可。 它也适用于Angular(TypeScript)。

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

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

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

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

更多推荐

本文发布于:2023-08-04 00:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1405175.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   数字键   对象   sort   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!