How to sort an array by values?
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 the sorting is done as if the data were not numeric.
Data.sort()
But the type of the die is numeric when I squeegee the following function: typeof(Data[0])
How do javascript sort data by values?
3 answers
Explanation:
By default, the JavaScript function sort()
lexically sorts your Array. But optionally you can pass a function in the input parameter, so that it returns the desired result.
About the sort () function:
Fate([sortfunction])
Description: sorts an array lexically by default, but a function can be passed in for sorting.
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 example in JSFiddle
Reference
If the values are just numbers, something like this can 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 entire interaction returns true.
A solution would be 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.