FreeCodeCampChina / freecodecamp.cn

FCC China open source codebase and curriculum. Learn to code and help nonprofits.

Home Page:https://fcc.asia/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question on array.sort()

zzusunjs opened this issue · comments

commented

Challenge Where do I belong has an issue.
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.
Please describe how to reproduce this issue, and include links to screenshots if possible.

My code:

function where(arr, num) {
  // 请把你的代码写在这里
  arr.sort(function(a,b){
    return a - b;
  });
  for(var i=0; i<arr.length; i++){
    if(arr[i] >= num){
      return i;
    }
  }
  return arr.length;
}

where([5,3,20,3], 3);

Did I have to write a comparable function to sort a number array ?
I found that arr = [4, 2, 5]; arr.sort(function(a, b){return a - b}); works.
But Why arr = [4, 2, 5]; arr.sort(); won't work ?

@zzusunjs

Did I have to write a comparable function to sort a number array?

Short answer is no. But in order to minimize the possibility of unexpected result regarding to the sort implementation of various JavaScript engines, it is stronly recommended that you do so.

I found that arr = [4, 2, 5]; arr.sort(function(a, b){return a - b}); works.

No wonder.

But Why arr = [4, 2, 5]; arr.sort(); won't work ?

It actually works (F.Y.I. I am on Chrome):
image

But obviously this wont' work, since the default sort is based off ASCII:
image

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort