[英]Javascript sort an array of objects based on numeric key
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 loop
使用。
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.但这是有角度的,所以普通的 Javascript 不起作用。
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.我认为它们必须是在循环之前对数组进行排序的某种方法,或者在循环中添加过滤器,不确定哪种方法是最好的。
But that is angular so normal Javascript it doesn't work.
但这是有角度的,所以普通的 Javascript 不起作用。
Simply you can use JavaScript sort function.只需使用 JavaScript 排序功能即可。 It will work in Angular(TypeScript) also.
它也适用于 Angular(TypeScript)。
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);
Use Array.prototype.sort
( doc ) and pass the compare function as you want:使用
Array.prototype.sort
( doc ) 并根据需要传递比较函数:
var data = [ { title: 'Shirt', position: 3 }, { title: 'Ball', position: 1, }, // add for actually seeing the correct result { title: 'Cake', position: 2, } ]; function compareFunction(a,b){ if(a.position > b.position) return 1; else return -1; } data.sort(compareFunction); console.log(data);
You can use arr.sort([compareFunction]).您可以使用 arr.sort([compareFunction])。
If compareFunction(a, b) is less than 0, sort a to an index lower than b, ie a comes first.如果 compareFunction(a, b) 小于 0,则将 a 排序到低于 b 的索引,即 a 在前。
If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements.如果 compareFunction(a, b) 返回 0,则使 a 和 b 彼此保持不变,但相对于所有不同元素进行排序。
If compareFunction(a, b) is greater than 0, sort b to an index lower than a, ie b comes first.如果 compareFunction(a, b) 大于 0,则将 b 排序到低于 a 的索引,即 b 在前。
compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments.当将特定的一对元素 a 和 b 作为两个参数时, compareFunction(a, b) 必须始终返回相同的值。 If inconsistent results are returned then the sort order is undefined.
如果返回不一致的结果,则排序顺序未定义。
For Example -例如 -
myarray.sort((a,b) => {
if(a.position > b.position)
return 1
else
return -1
})
Here is a bubble sort approach:这是一种冒泡排序方法:
var data = [
{
title: 'Shirt',
position: 3
},
{
title: 'Ball',
position: 1,
},
{title: "h",
position:0}
]
for(let i=0;i<data.length;i++)
for(let j=0;j<data.length - 1;j++){
if(data[j].position > data[j + 1].position){
var first = data[j]
var second = data[j + 1]
data[j] = second;
data[j + 1] = first;
}
}
console.log(data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.