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 :
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.
This callback receive elements to iterate, and you can compare values, if return true, switch order of elements, for ie:
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:
arr.sort((a, b) => parseInt(a.age) > parseInt(b.age))
I think you can use localeCompare() to compare strings. 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);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.