如何通过Javascript中的值对关联数组进行排序? [英] How to sort an associative array by its values in Javascript?
问题描述
我有关联数组:
array["sub2"] = 1;
array["sub0"] = -1;
array["sub1"] = 0;
array["sub3"] = 1;
array["sub4"] = 0;
按其值排序(降序)的最优雅方法是什么,结果将是一个按此顺序具有相应索引的数组:
What is the most elegant way to sort (descending) by its values where the result would be an array with the respective indices in this order:
sub2, sub3, sub1, sub4, sub0
推荐答案
Javascript 没有您想象中的关联数组".相反,您只需能够使用类似数组的语法来设置对象属性(如您的示例中所示),以及迭代对象属性的能力.
Javascript doesn't have "associative arrays" the way you're thinking of them. Instead, you simply have the ability to set object properties using array-like syntax (as in your example), plus the ability to iterate over an object's properties.
这样做的结果是,无法保证迭代属性的顺序,因此对于它们来说没有什么比排序更合适的了.相反,您需要将对象属性转换为真实"数组(它可以保证顺序).这是一个代码片段,用于将对象转换为双元组(双元素数组)数组,按照您的描述对其进行排序,然后对其进行迭代:
The upshot of this is that there is no guarantee as to the order in which you iterate over the properties, so there is nothing like a sort for them. Instead, you'll need to convert your object properties into a "true" array (which does guarantee order). Here's a code snippet for converting an object into an array of two-tuples (two-element arrays), sorting it as you describe, then iterating over it:
var tuples = [];
for (var key in obj) tuples.push([key, obj[key]]);
tuples.sort(function(a, b) {
a = a[1];
b = b[1];
return a < b ? -1 : (a > b ? 1 : 0);
});
for (var i = 0; i < tuples.length; i++) {
var key = tuples[i][0];
var value = tuples[i][1];
// do something with key and value
}
你可能会发现把它包装在一个接受回调的函数中更自然:
You may find it more natural to wrap this in a function which takes a callback:
function bySortedValue(obj, callback, context) {
var tuples = [];
for (var key in obj) tuples.push([key, obj[key]]);
tuples.sort(function(a, b) {
return a[1] < b[1] ? 1 : a[1] > b[1] ? -1 : 0
});
var length = tuples.length;
while (length--) callback.call(context, tuples[length][0], tuples[length][1]);
}
bySortedValue({
foo: 1,
bar: 7,
baz: 3
}, function(key, value) {
document.getElementById('res').innerHTML += `${key}: ${value}<br>`
});
<p id='res'>Result:<br/><br/><p>
这篇关于如何通过Javascript中的值对关联数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!