How to sort an array by values?

Asked

Viewed 24,782 times

15

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 sort is done as if the data were not numerical.

Data.sort()

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

How to do javascript to sort data by values?

3 answers

10


Explanation:

By default, the function sort() javascript 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():

Sort([sortfunction])

Description: sorts a lexical array by default, but a function can be passed for sorting.

Parameters:

sortFunction (Function) optional:

A function that returns the desired order to be used in the 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

3

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.

1

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 accept to be called with a parameter that is a comparison function.

Documentation of sort on MDN

  • Only one function as a method parameter sort() returning a-b would solve.

  • Yeah, I already edited it! I ended up discovering it too, there in the MDN documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.