3

Example:

console.log(f(['12dh', '8-4', '66']))
//output should be => ['8-4', '66', '12dh']
dda
  • 6,030
  • 2
  • 25
  • 34
VRaja
  • 33
  • 5
  • 2
    Array.sort will help you – kolodi Apr 13 '16 at 16:59
  • console.log(['12dh', '8-4', '66'].reverse()) will give you reverse sort order. But your expected output above is not reverse alphabetical. It is something else. Reverse alphabetical would yield: ["66", "8-4", "12dh"]. If you need something custom, you'll have to write a sort function. See this: http://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects – Perry Tew Apr 13 '16 at 17:04
  • Thanks that was helpful – VRaja Apr 13 '16 at 17:06

2 Answers2

2

You can do this very easily with sort and reverse.

var array = ['12dh', '8-4', '66'];

var sorted = array.sort().reverse();

console.log(sorted);

You can also wrap it in a function.

function sortReverse(array){
    return array.sort().reverse();
}

Also if you're concerned about performance you can pass a custom comparison function to sort:

array.sort(function(a,b){
   return a < b;
});

This could be quicker when dealing with larger arrays, because it doesn't have to reverse after sorting.

To filter anything that doesn't start with a number:

array.filter(function(str){
   return !isNaN(str.charAt(0));
}).sort().reverse();
Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57
0

You can do something like that:

var array = ['12dh', '8-4', '66'];
array.sort(function (a, b) {
    if (a > b) {
        return -1;
    }
    if (a < b) {
        return 1;
    }
    return 0;
});

I hope that helps :D

Fabricio
  • 3,248
  • 2
  • 16
  • 22