I'm trying to create a function that finds the xth greatest element in an array. The code below works great if all integers are positive but messes up once a negative number is in the array. For example:
When calling the function with fun([-10,-25,-47,-36,0], 1). The output should be 0 but it gives -47.
How can I make this function work for both positive and negative numbers?
const fun = (x, y) => {
let sorted = x.sort(function(a, b) {
return a-b;
});
let el = x[y -1];
console.log(el);
}
x being the array of integers and y being the xth greatest element
To sort the numbers in descending order, you should use b - a
(second element minus first element).
This allows you to grab the greatest number in the array, like this:
const greatest = (x, y) => { // After this call, the array `x` will be sorted x.sort(function(a, b) { return b - a; }); let el = x[y - 1]; console.log(el); return el; } // First greatest number among those in the array greatest([1, 3, 5], 1); // excepted: 5 greatest([30, 5, 11], 1); // excepted: 30 greatest([-3, -19, -11], 1); // excepted: -3 greatest([1000000, 999999, -1000000], 1); // excepted: 1000000 greatest([Number.POSITIVE_INFINITY, 0, 10000 * 10000 * 10000], 1); // excepted: Infinity greatest([Number.NEGATIVE_INFINITY, 0, -10000 * 10000 * 10000], 1); // excepted: 0 greatest([Number.NaN, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY], 1); // excepted: NaN
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.