Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort javascript array in object, maintaining key

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!

like image 535
mattyd Avatar asked Apr 09 '12 23:04

mattyd


People also ask

How do you sort an array of objects by key value?

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.

How do you sort a key value array?

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

How do you sort an array of objects in JavaScript?

To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.


2 Answers

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]});
}
like image 160
jpsimons Avatar answered Nov 02 '22 23:11

jpsimons


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);
});
like image 29
Mohsen Avatar answered Nov 03 '22 01:11

Mohsen