var data = [
{name: 'uc', value: 5},
{name: 'amap', value: 2},
{name: 'ali', value:3}
...
]
解决代码如下
function sortFn( parameter ){
return function(a,b){
var value1 = a[parameter]
var value2 = b[parameter]
return value1-value2;
}
}
var result = data.sort(sortFn('value'));
consele.log(result);
输出结果:
这里可能会有人忘记了sort()方法的用法
例:
按字母排序:
<script type="text/javascript">
var arr = new Array(6)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
arr[3] = "James"
arr[4] = "Adrew"
arr[5] = "Martin"
document.write(arr + "<br />")
document.write(arr.sort())
</script>
输出:
George,John,Thomas,James,Adrew,Martin
Adrew,George,James,John,Martin,Thomas
<script type="text/javascript">
var arr = new Array(6)
arr[0] = "10"
arr[1] = "5"
arr[2] = "40"
arr[3] = "25"
arr[4] = "1000"
arr[5] = "1"
document.write(arr + "<br />")
document.write(arr.sort())
//输出
//10,5,40,25,1000,1
//1,10,1000,25,40,5
</script>
请注意,上面的代码没有按照数值的大小对数字进行排序,要实现这一点,就必须使用一个排序函数:
<script type="text/javascript">
function sortNumber(a,b)
{
return a - b
}
var arr = new Array(6)
arr[0] = "10"
arr[1] = "5"
arr[2] = "40"
arr[3] = "25"
arr[4] = "1000"
arr[5] = "1"
document.write(arr + "<br />")
document.write(arr.sort(sortNumber))
//输出
//10,5,40,25,1000,1
//1,5,10,25,40,1000
</script>