Sort a numbered array inside a function

I am very new to coding and even new to Javascript. I have done some basic courses, and I myself start to study on my own. I tried to search to answer this question and did not find anything like it. If someone can find this answer, please let me know!

I am trying to write a function that will take a list of numbers (like an array) and sort it from smallest to largest. Since I understand that sort () does not sort numbers correctly, I am trying to write this function based on some search queries that I made.

Here is what I have and honestly, I feel that I am missing a step:

var sort= function(list){
    function numberSort (a, b) {
        return a - b;
    };
    numberSort(list);

I get a syntax error. I find it difficult to figure out how to get through an input (list) through an internal function so that sorting can happen.

Can someone explain what is wrong here? I feel that I'm not too sure about the function I found, which helps in sorting numbers.

Thank!

+4
source share
3 answers

All you need is a valid callback that returns a value for each check of the two elements and their relationship, the number is less than zero, zero or more than zero, depending on the order.

You can look Array#sortfor more information.

var array = [4, 6, 7, 2, 3, 10, 43, 100];

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

console.log(array);
Run codeHide result
+2
source

Sorting is used directly in the array, and you pass a function to determine what comes first. try the following:

var myArray = [1,2,5,3,11,7,458,90000,9001,-53,4,1.546789];
function myFunc(a,b){
  return a-b;
}
console.log(myArray.sort(myFunc));
Run codeHide result
+2
source

, , .

var sort = function(list){
function selectionSort(list) {
    for(var i=0;i<list.length-1;i++){
        for(var j=i+1;j<list.length;j++){
        if(list[i]>list[j]){
            var temp = list[j];
            list[j] = list[i];
            list[i] = temp;         
        }}}
    return list;
};
return selectionSort(list);
}

var list = [6,4,2,3,5];
var result = sort(list);
console.log(result);
0

Source: https://habr.com/ru/post/1660710/


All Articles