Riadan414
Riadan414

Reputation: 51

Sorting a numbered array within a function

I am very new at coding and even newer at Javascript. I've done some basic courses and I'm trying to start learning through challenges on my own. I tried to search to see if this question was answered and didn't find anything similar. If someone can find this answer, please let me know!

I am trying to write a function that will take a list of numbers (as an array) and sort it from least to greatest. Since I understand that sort() doesn't sort numbers correctly, I am trying to write this function based on some googling I did.

Here's what I have and honestly, it feels like I'm missing a step:

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

I'm getting a syntax error. I'm having trouble understanding how to pass through the input (list) through the inner function so that the sort can happen.

Could anyone provide further explanation of what's wrong here? I feel like I'm not too solid on the function I found that helps with sorting numbers.

Thanks!

Upvotes: 4

Views: 53

Answers (3)

Hitesh Kalwani
Hitesh Kalwani

Reputation: 573

short selection sort example for beginner level, Hope you will find it useful.

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);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386654

All you need is the right callback which returns a value for every check of two elements and their relation, a number smaller than zero, zero or greater than zero, depending on the order.

You may have a look to Array#sort for further information.

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

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

console.log(array);

Upvotes: 2

Feathercrown
Feathercrown

Reputation: 2591

Sort is used on an array directly, and you pass in a function to determine which goes first. try this:

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));

Upvotes: 2

Related Questions