How to sort an array by values?

11

Suppose I have the following data.

Data = [3,5,1,7,3,9,10];

If I try to use the sort method in this array, sorting is done as if the data were not numeric.

Data.sort()

But the data type is numeric when I run the following function: typeof(Data[0])

How to make javascript sort data by values?

    
asked by anonymous 20.03.2014 / 13:37

3 answers

5

Explanation:

By default, the sort() function in javascript sorts your Array. But optionally you can pass a function on the input parameter so that it returns the desired result.

About the sort () function:

  

sort )      

Description: sorts an array in lexical form by default, however a function can be passed to sort.

     

Parameters:

     

sortFunction (function) optional :

     

A function that returns the desired order to be used in sort() .

Example:

function sortfunction(a, b){
  return (a - b) //faz com que o array seja ordenado numericamente e de ordem crescente.
}
Data = [3,5,1,7,3,9,10];
Data.sort(sortfunction); //resultado: [1, 3, 3, 5, 7, 9, 10]

Functional sample in JSFiddle

Reference

    
20.03.2014 / 14:32
2

If values are just numbers, something like this might solve:

array.sort(function(a, b){

    return a > b;

});

In this case I am comparing each value in the Array with the next value, establishing a criterion that one is greater than the other and returning the comparison. This function will be repeated by traversing the array until the integer interaction returns true.

    
20.03.2014 / 13:40
1

A solution would look like this:

Data = [3,5,1,7,3,9,10];

Data.sort(function(a,b) {
    return a - b;
});

var str = "";
for (var it = 0; it < Data.length; it++) {
    str += Data[it] + ",";
}

alert(str);

jsfiddle

What happens is that the function sort accepts to be called with a parameter that is a comparison function.

Documentation of sort in MDN

    
20.03.2014 / 14:05