Sorting a value pair in Javascript - Stack Overflow

I must be missing the proper term or else I'm sure I could find the answer by searching... in any

I must be missing the proper term or else I'm sure I could find the answer by searching... in any case, here's what I want to do.

Through javascript, I get four variables (A, B, C, and D) that I would like to sort, and still keep track of the variable name (since it's encoded with meaning information).

Sample Data:

A = 2;
B = 1;
C = 4;
D = 3;

What I need to do now is sort them in value order (4,3,2,1) such that I can actually know the variable name ordering (C,D,A,B).

I must be missing the proper term or else I'm sure I could find the answer by searching... in any case, here's what I want to do.

Through javascript, I get four variables (A, B, C, and D) that I would like to sort, and still keep track of the variable name (since it's encoded with meaning information).

Sample Data:

A = 2;
B = 1;
C = 4;
D = 3;

What I need to do now is sort them in value order (4,3,2,1) such that I can actually know the variable name ordering (C,D,A,B).

Share Improve this question asked Sep 25, 2012 at 3:23 Bradley M. DavisBradley M. Davis 881 silver badge8 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

You can keep an array of value pair objects and then simply sort that array. Of course, the array's sort method need to know how to interpret the object but that can be done by supplying a parison function to the sort method.

First declare your array of objects:

sample_data = [
  { name: 'A', value: 2 },
  { name: 'B', value: 1 },
  { name: 'C', value: 4 },
  { name: 'D', value: 3 }
];

Then write a parison function:

function custom_pare (a,b) {
  // I'm assuming all values are numbers
  return a.value - b.value;
}

Then simply sort and reverse:

sample_data.sort(custom_pare).reverse();

To print out the sorted names simply iterate through the array:

for (var i=0;i<sample_data.length;i++) {
  console.log(sample_data[i].name);
}

May it help you:

https://github./shinout/SortedList

This is sortedlist library.

I think what you should be looking for something like "Associative arrays" implemented in Javascript.

Check this earlier thread for your answer.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742385322a4433940.html

相关推荐

  • Sorting a value pair in Javascript - Stack Overflow

    I must be missing the proper term or else I'm sure I could find the answer by searching... in any

    2天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信