[英]How to sort an array of objects by one of the objects string values numerically?
I have an array of objects similar to this : 我有一个类似于以下对象的数组:
var this array = [
{
"id" : "A20",
"age" : "16"
},
{
"id" : "A2",
"age" : "12"
},
{
"id" : "B16",
"age" : "45"
}]
I need to sort this array by their ID, So it would end up like : 我需要按其ID对这个数组进行排序,所以最终会像这样:
this array = [
{
"id" : "A2",
"age" : "12"
},
{
"id" : "A20",
"age" : "16"
},
{
"id" : "B16",
"age" : "45"
}]
I have this method of sorting : 我有这种排序方法:
nodes.sort(function(a,b){
// console.log(a.Pos)
// console.log(a.pinNum)
var alc = a.id, blc = b.id;
console.log(alc)
return alc > blc ? 1 : alc < blc ? -1 : 0;
});
But this only works alphabetically. 但这只能按字母顺序工作。 I have also found this but it gives back just the strings I pass to the function not the array of objects : 我也发现了这一点,但它只返回传递给函数的字符串,而不是对象数组:
function sortArray(arr) {
var tempArr = [],
n;
console.log(arr)
for (var i in arr) {
var thisString = arr[i].id;
// tempArr[i] = arr[i].match(/([^0-9]+)|([0-9]+)/g);
tempArr[i] = thisString.match(/([^0-9]+)|([0-9]+)/g);
for (var j in tempArr[i]) {
if (!isNaN(n = parseInt(tempArr[i][j]))) {
tempArr[i][j] = n;
}
}
}
tempArr.sort(function (x, y) {
for (var i in x) {
if (y.length < i || x[i] < y[i]) {
return -1; // x is longer
}
if (x[i] > y[i]) {
return 1;
}
}
return 0;
});
for (var i in tempArr) {
arr[i] = tempArr[i].join('');
}
return arr;
}
console.log(sortArray(nodes).join(","));
What I need is the second sorting function but with the ability to sort both alphabetically and numerically. 我需要的是第二个排序功能,但具有按字母和数字排序的功能。 Thanks 谢谢
var array = [{
"id" : "A20",
"age" : "16"
}, {
"id" : "A2",
"age" : "12"
}, {
"id" : "B16",
"age" : "45"
}];
array.sort(function(a, b) {
var aSplit = /(\D*)(\d*)/.exec(a.id),
bSplit = /(\D*)(\d*)/.exec(b.id);
if( aSplit[1] !== bSplit[1] )
return aSplit[1].localeCompare(bSplit[1]);
else
return aSplit[2] - bSplit[2];
});
Use function .sort in array, and pass has argument, a callback. 在数组中使用.sort函数,并传递具有参数的回调。
This callback receive elements to iterate, and you can compare values, if return true, switch order of elements, for ie: 此回调接收要迭代的元素,并且可以比较值(如果返回true),请切换元素的顺序,例如:
arr.sort(function(a, b) {
return parseInt(a.age) > parseInt(b.age))
};
or, if you use ecma script 6, you can use arrow function, is better, ie below: 或者,如果您使用的是ecma脚本6,则可以使用箭头功能更好,例如:
arr.sort((a, b) => parseInt(a.age) > parseInt(b.age))
Docs here: http://www.w3schools.com/jsref/jsref_sort.asp 此处的文档: http : //www.w3schools.com/jsref/jsref_sort.asp
I think you can use localeCompare() to compare strings. 我认为您可以使用localeCompare()比较字符串。 Try this code, it should work: 试试下面的代码,它应该可以工作:
nodes.sort(function(a,b){
// console.log(a.Pos)
// console.log(a.pinNum)
var alc = a.id, blc = b.id;
console.log(alc)
return alc.localeCompare(blc);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.