0

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 ] ......]
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
ellier7
  • 417
  • 4
  • 9
  • 23
  • 2
    possible duplicate: http://stackoverflow.com/questions/16096872/how-to-sort-2-dimensional-array-by-column-value – Doua Beri Aug 03 '16 at 01:56
  • First, you're going to want to take a look at [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) You'll need to write a comparison function that compares the second value of each array element, and then compares the first if the second values are equal. The examples in the documentation should be a good starting point. – S McCrohan Aug 03 '16 at 01:54

2 Answers2

1

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/

Usir
  • 21
  • 4
  • That results in: [ [ 'i', 7 ], [ 'l', 3 ], [ 's', 3 ], [ 'c', 3 ], [ 'a', 3 ], [ 'e', 2 ], [ 'o', 2 ], [ 'p', 2 ], [ 'r', 2 ], [ 'u', 2 ], [ 'g', 1 ], [ 'f', 1 ], [ 'd', 1 ], [ 't', 1 ], [ 'x', 1 ] ] – ellier7 Aug 03 '16 at 02:11
0

The sort method in Array

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.

tomision
  • 964
  • 9
  • 22