Reputation: 427
I have an array that is currently sorted by the first value:
[ [ 'a', 3 ],
[ 'c', 3 ],
[ 'd', 1 ],
[ 'e', 2 ],
[ 'f', 1 ],
[ 'g', 1 ],
[ 'i', 7 ],
[ 'l', 3 ],
[ 'o', 2 ],
[ 'p', 2 ],
[ 'r', 2 ],
[ 's', 3 ],
[ 't', 1 ],
[ 'u', 2 ],
[ 'x', 1 ] ]
I would like to sort the digits in descending order to get:
[ [ 'i', 7 ],
[ 'a', 3 ],
[ 'c', 3 ],
[ 'l', 3 ],
[ 's', 3 ],
[ 'e', 2 ],
[ 'o', 2 ] ......]
Upvotes: 0
Views: 1964
Reputation: 21
Use Array.sort([compareFunction])
function comparator(a, b) {
if (a[1] > b[1]) return -1
if (a[1] < b[1]) return 1
return 0
}
myArray = myArray.sort(comparator)
edit for comment:
Here is a jslint showing it in action: https://jsfiddle.net/49ed0Lj4/1/
Upvotes: 1
Reputation: 994
var arr = [
['a', 3],
['c', 3],
['d', 1],
['e', 2],
['f', 1],
['g', 1],
['i', 7],
['l', 3],
['o', 2],
['p', 2],
['r', 2],
['s', 3],
['t', 1],
['u', 2],
['x', 1]
];
arr.sort(function(a, b) {
return b[1] - a[1]
})
Maybe you need to sort by both the English letters and number. You can change the callback function to do this.
Upvotes: 0