简体   繁体   English

在Javascript中对值对进行排序

[英]Sorting a value pair in Javascript

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). 通过javascript,我得到了四个我想要排序的变量(A,B,C和D),并且仍然跟踪变量名称(因为它是用含义信息编码的)。

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). 我现在需要做的是按值顺序(4,3,2,1)对它们进行排序,这样我才能真正知道变量名称排序(C,D,A,B)。

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 comparison function to the sort method. 当然,数组的sort方法需要知道如何解释对象,但这可以通过向sort方法提供比较函数来完成。

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 comparison function: 然后写一个比较函数:

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

Then simply sort and reverse: 然后简单地排序和反转:

sample_data.sort(custom_compare).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.com/shinout/SortedList https://github.com/shinout/SortedList

This is sortedlist library. 这是sortedlist库。

I think what you should be looking for something like " Associative arrays " implemented in Javascript. 我认为你应该寻找像Javascript中实现的“ 关联数组 ”之类的东西。

Check this earlier thread for your answer. 检查这个早期的主题以获得答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM