2012-10-08 251 views
6

可能重复:
How to sort an associative array by its values in Javascript?如何按值排序(关联)数组?

所以第一关,我知道在技术上JavaScript没有关联数组,但我不知道如何标题,并传达出正​​确的想法。

因此,这里是我的代码有,

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

而且我想通过值,从而进行排序,当我依次通过它以后ROB至上,然后BOB

我已经试过,

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

但他们都没有实际上做任何事情。

将数组输出到控制台之前和之后结果以相同的顺序出来。

+4

也就是说JS数组的错误使用。仅对数组使用数字键。 '.sort'不会做任何事情,因为严格来说你的数组没有任何元素。在这种情况下你必须使用对象。我推荐阅读[MDN - 使用对象(https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects)。 –

+2

另外:[由属性值排序JavaScript对象(http://stackoverflow.com/questions/1069666/sorting-javascript-object-by-property-value)。 –

+0

虽然标记为重复,但下面列出的解决方案并未在副本中提及。 – PopeJohnPaulII

回答

21

数组只能有数字索引。您需要将其重写为对象或对象数组。

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方法,你可以对它进行排序:

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

我喜欢这种(数组)方法,用'val'调用和排序的正确方法是什么? – PopeJohnPaulII

+0

我已经更新了我的答案,包括用'val'与对象数组进行排序。 – saml

+0

伟大而简单的解决方案。 – Ahsan

2

第一 - 这是不正确创建阵列使用它作为一个映射。而是使用Object:

var status = {}; 
status['BOB'] = 10; 

该数组是一个具有处理数字顺序索引的逻辑的类。

现在回答你的反应,映射没有秩序,没有关于它会遍历所以称为“排序的映射”

没有这样的事情我sugest你使用与对象数组顺序保证键,值:

var status = []; 
status.push({ key: 'BOB', value: 10 }); 

两个数组:

var status = { 
    keys: [], 
    values: [] 
}; 
status.keys.push('BOB'); 
status.value.push(10); 

这取决于您的需求。

1

你应该使用JavaScript对象数组里面:jsfidle

 var status = new Array(); 
    status.push({key: 'BOB', value: 10}); 
    status.push({key: 'TOM', value: 3}); 
    status.push({key: 'ROB', value: 22}); 
    status.push({key: 'JON', value: 7}); 
    status.sort(function(a, b){ 

     if(a.value > b.value){ 
     return -1; 
     } 
     else if(a.value < b.value){ 
     return 1; 
     } 
     return 0; 
    }); 
+0

这是很好的字符串比较 – cw24

2

“阵列” 在JavaScript中的数字索引。 “对象”是你会称之为关联数组的东西。 “对象”本质上是无序的。

所以要做到这一点,你需要改变你的数据结构。

var arr = []; // Array 

// push a few objects to the array. 
arr.push({name: 'BOB', age: 10}); 
arr.push({name: 'TOM', age: 3}); 
arr.push({name: 'ROB', age: 22}); 
arr.push({name: 'JON', age: 7}); 

var sorted = arr.sort(function(a, b) { 
    return a.age - b.age; 
}); 

console.log(sorted); 

enter image description here

+0

如何按名称排序? –