Big to Small List Sorting

I wanted to return the largest number at integer[0]

list1= [4,6,2,1,9,63,-134,566]


var max = function(list)
{
 var bigToSmallList=[] //makin an empty list to return the biggest value at position 0
 list.sort() // sorting it into numerical order small to big
 
 
 for(i=list.length;i<list.length;i--) //want to iterate from the end to the start 
 {
    bigToSmallList.push(list[i])//adding next largest to list
    console.log(bigToSmallList) //just checking what's up 
 }


 return bigToSmallList[0]; //should return the biggest value at position 0
}

max(list1)

Seems to just return undefined?

Using sort without any argument only sorts the elements as if they are strings instead of numbers. You need to add a compare function to sort numbers as you are wanting. Take a look at the sort documentation for examples of how to accomplish this.

Also, your for loop condition above is not correct. Take your example array of [4,6,2,1,9,63,-134,566]. It has a length of 8, that means i starts at the value 8. The condition which allows the for loop to keep iterating starts by checking if 8 is less than 8. This evaluates to false, so the for loop never starts and bigToSmallList never gets any values added to it. So, when you try to reference bigToSmallList[0] in your return statement, you return undefined, because there is not item in the first index (0).


var min = function(list){
    
    return Math.min.apply(null, list)
}

This works

var min = function(list){
    
    return Math.min(null, list)
}

This doesnt

var min = function(list){
    
    return Math.min(list)
}

Messing about with the Math.min and max methods and not sure why it doesnt work

what does the apply and null do and why is it necessary?

Math.min() takes single values as arguments.
list is an array and not a single value.
You can spread the array.

how do you spread an array or list?

In ES6 you can spread an array using the spread operator: …array

Example:

let arr = [1, 2, 3]
let arr2 = [...arr, 4, 5]
console.log(arr2) // returns [1, 2, 3, 4, 5]

For your use case, you could use return Math.min(...list);