gpt4 book ai didi

javascript - 如何按 Javascript 中的值对关联数组进行排序?

转载 作者:IT王子 更新时间:2023-10-29 02:46:19 26 4
gpt4 key购买 nike

我有关联数组:

array["sub2"] = 1;
array["sub0"] = -1;
array["sub1"] = 0;
array["sub3"] = 1;
array["sub4"] = 0;

按其值排序(降序)的最优雅方法是什么,结果将是一个数组,其中相应的索引按此顺序排列:

sub2, sub3, sub1, sub4, sub0

最佳答案

Javascript 并不像您想象的那样拥有“关联数组”。相反,您只需能够使用类似数组的语法设置对象属性(如您的示例中所示),以及迭代对象属性的能力。

这样做的结果是无法保证您迭代属性的顺序,因此没有什么比它们更合适的了。相反,您需要将对象属性转换为“真正的”数组(保证顺序)。这是一个代码片段,用于将对象转换为二元组数组(双元素数组),按照您的描述对其进行排序,然后对其进行迭代:

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
}

您可能会发现将它包装在一个接受回调的函数中更自然:

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 - 如何按 Javascript 中的值对关联数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5199901/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com