I have a javascript object with two array's as shown,
var Object = {'name': [Matt, Tom, Mike...], 'rank': [34,1,17...]};
I am trying to sort by rank 1,2,3.. but keep the name associated with the rank.
Object.name[0] // tom
Object.rank[0] // tom's rank of 1.
Should I reconfigure my object to make sorting easier?
I am currently using the
Object.rank.sort(function(a,b){return a-b});
to order rank, but the name does not stay with it.
All help appreciated. Thanks!
The objects can contain key-value pair and have properties and values. We can sort the array of objects using the sort() method in javascript and then provide a comparison function that will ultimately determine the order of the objects. A compare Function applies rules to sort arrays that are defined by our logic.
There are four functions for associative arrays — you either array sort PHP by key or by value. To PHP sort array by key, you should use ksort() (for ascending order) or krsort() (for descending order). To PHP sort array by value, you will need functions asort() and arsort() (for ascending and descending orders).
To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.
Yes, reconfigure. Say you had this instead:
var people = [{name:"Matt", rank:34}, {name:"Tom", rank:1}, {name:"Mike", rank:17}];
Then you could sort like this:
people.sort(function(a, b) {
return a.rank - b.rank;
}
Edit
Since you have parallel lists, just zip them together:
var people = [];
for (var i = 0; i < Object.name.length; i++) {
people.push({name:Object.name[i], rank:Object.rank[i]});
}
The real world object:
o = {name: ['Matt', 'Tom', 'Mike'], rank: [34,1,17]};
Make an array for better data structure:
var arr =[];
o.name.forEach(function(name, i){
arr.push({name: name, rank: o.rank[i]})
});
Sort by rank:
arr.sort(function(a,b){return a.rank - b.rank});
Sort by name:
arr.sort(function(a,b){return a.name- b.name});
Revert back to your original data structure:
o = {name:[], rank:[]}
arr.forEach(function(item){
o.name.push(item.name);
o.rank.push(item.rank);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With