Mastikhor Mastikhor - 4 months ago 10
Javascript Question

How to Sort/Ordering of array list of array that start with the charecter not numeric in JQUERY?

I have an Array :

data =["c3.2xlarge","c3.4xlarge","c3.large"];


it's alphabetical now and sorted, but that gives us when we really want
c3.large
to appear first.

How do I create a function to sort the objects like this?

Answer
  • Array Sort() Method sorts the elements in the array
  • You'll need to tweak the sorting function to get the results you're after

http://fiddle.jshell.net/63z6j0rc/

var myArr = ["c3.2xlarge","c3.4xlarge","c3.large"];

//sort by strings
myArr.sort(function(val1, val2){
    return val1.replace(/\D+/g, "") - val2.replace(/\D+/g, "");  
});

$('#result').html(myArr[0] + ' ' + myArr[1] + ' ' + myArr[2] + '<br>');

// Result : c3.large c3.2xlarge c3.4xlarge

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort arr.sort([compareFunction])

Comments