简体   繁体   中英

Same code runs differently on different devices

I'm new to coding, still learning. My friend gave me a task to write a function that does return the 2nd highest number from an array, I've managed to do it using array.prototype.sort(). He said to replace "-" with a "<" or ">" to make the code more clear, that's where the problem started.

I'm using VCS on windows, and it's not working properly. My friend uses a mac, everything works fine. Tried it on jsfiddle, everything works fine.

const secondMax = (arr) => {
  return arr.sort((a, b) => b - a)[1]; //does return the correct number after console.log()
};
const secondMax = (arr) => {
  return arr.sort((a, b) => a < b)[1]; //does not
};

"a < b" should be sorting descending "a > b" should be sorting ascending But no matter which operator I use, the sorting fails and just returns the second number from the array

You're supposed to return a number, not a boolean. So the first is correct. The latter might work by chance on some javascript engines, but it's not guaranteed to.

sort sorts the array as String by default. If you pass a comparator, then it's a function which will depend on two parameters and return :

  • negative, if the first parameter is smaller than the second
  • 0 if they are equal
  • positive, if the first parameter is greater than the second

Using a logical operator instead of the above is mistaken.

However, if you are interested in finding the second largest number, then it's better to do it using a cycle:

var largestNumbers = [];
var firstIndex = (arr[0] < arr[1]) ? 1 : 0;
largestNumbers.push(arr[firstIndex]);
largestNumbers.push(arr[1 - firstIndex]);
for (var i = 2; i < arr.length; i++) {
    if (largestNumbers[1] < arr[i]) {
        if (largestNumbers[0] < arr[i]) {
            largestNumbers[1] = largestNumbers[0];
            largestNumbers[0] = arr[i];
        }
    }
}

This is quicker than sorting an array and more importantly, it does not destroy your initial order just to find the second largest number.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM