Home > front end >  How would I make 'arr' a function in order to use 'arr.sort' when not setting a
How would I make 'arr' a function in order to use 'arr.sort' when not setting a

Time:11-11

I want to create a function to find the lowest value within a set of numbers, but I do not wish to use the Math.min(); method. Below is my code I have constructed:

function min(arr) {
    var lowest = arr.sort((x, y) => x - y);
    return lowest[0];
}

but 'arr.sort' is not a function, as it has not been defined for obvious reasons: I want to be able to input any array into the 'min' function.

I tried creating a JavaScript function for finding the lowest value in an array of numbers, expecting to have a function that would accept any array and would output the lowest value in that array.

CodePudding user response:

I want to create a function to find the lowest value within a set of numbersfunction to find the lowest value within a set of numbers

Just pop the sorted array

That is assuming you are calling your function with an actual array and you do not mind that array is modified

const min = arr => arr.sort((a, b) => b - a).pop();


console.log(min([7,6,8,99,100]))
console.log(min([1000,999,998,997]))
const arr1 = [1000,999,998,997]
console.log("---------------")
console.log(arr1)
console.log(min(arr1))
console.log(arr1)

CodePudding user response:

function min(arr) {
    arr.sort( (a, b) => a - b );
    return arr[0]
}

Pay attention, though, that sort() overwrites the original array.

  • Related