How does Javascript's sort() work?

前端 未结 9 1784
长情又很酷
长情又很酷 2020-11-22 11:06

How does the following code sort this array to be in numerical order?

var array=[25, 8, 7, 41]

array.sort(function(a,b){
  return a - b
})
9条回答
  •  孤街浪徒
    2020-11-22 11:49

    Deeply Knowledge

    If the result is negative a is sorted before b.

    If the result is positive b is sorted before a.

    If the result is 0 no changes are done with the sort order of the two values.

    NOTE:

    This code is the view inside of the sort method step by step.

    OUTPUT:

    let arr = [90, 1, 20, 14, 3, 55];
    var sortRes = [];
    var copy = arr.slice();		//create duplicate array
    var inc = 0;	//inc meant increment
    copy.sort((a, b) => {
    	sortRes[inc] = [ a, b, a-b ];
    	inc += 1;
    	return a - b;
    });
    var p = 0;
    for (var i = 0; i < inc; i++) {
    	copy = arr.slice();
    	copy.sort((a, b) => {
    		p += 1;
    		if (p <= i ) {
    			return a - b;
    		}
    		else{
    			return false;
    		}
    	});
    	p = 0;
    	console.log(copy +' \t a: '+ sortRes[i][0] +' \tb: '+ sortRes[i][1] +'\tTotal: '+ sortRes[i][2]);
    }

提交回复
热议问题