如何按值对(关联)数组进行排序? [英] How to sort an (associative) array by value?

查看:210
本文介绍了如何按值对(关联)数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

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

首先,我知道技术上Javascript没有关联数组,但我不确定如何标题并获得正确的想法。

So first off I know technically Javascript doesn't have associative arrays, but I wasn't sure how to title it and get the right idea across.

所以这是我的代码,

var status = new Array();
status['BOB'] = 10
status['TOM'] = 3
status['ROB'] = 22
status['JON'] = 7

我想按值排序,以便稍后在上循环播放首先是ROB ,然后是 BOB 等。

And I want to sort it by value such that when I loop through it later on ROB comes first, then BOB, etc.

我试过了,

status.sort()
status.sort(function(a, b){return a[1] - b[1];});

但他们似乎都没有做任何事情。

But none of them seem to actually DO anything.

将阵列打印到控制台之前和之后会导致它以相同的顺序出现。

Printing the array out to the console before and after result in it coming out in the same order.

推荐答案

数组只能有数字索引。您需要将其重写为Object或Object of Array。

Arrays can only have numeric indexes. You'd need to rewrite this as either an Object, or an Array of Objects.

var status = new Object();
status['BOB'] = 10
status['TOM'] = 3
status['ROB'] = 22
status['JON'] = 7

var status = new Array();
status.push({name: 'BOB', val: 10});
status.push({name: 'TOM', val: 3});
status.push({name: 'ROB', val: 22});
status.push({name: 'JON', val: 7});

如果您喜欢 status.push 方法,您可以使用以下方式对其进行排序:

If you like the status.push method, you can sort it with:

status.sort(function(a,b) {
    return a.val - b.val;
});

这篇关于如何按值对(关联)数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆