简体   繁体   中英

IE Array.sort not sorting with compare function

Here is the code example which is not working properly in IE 11.

Element with id = END3 should be the last one.

Just don't tell me that I need to write sorting manually. It is not a big deal to implement it, but really?!

 var list = [{ id: "SP1" }, { id: "SP4" }, { id: "END3" }, { id: "SP2" } ]; console.log( list.sort(function(a, b) { if (a.id === "END3") { return 1; } return 0; }) ); 

Return -1 instead of 0 in the else block. When the compare method returns 0 it leaves a and b unchanged.

 var list = [{ id: "SP1" }, { id: "SP4" }, { id: "END3" }, { id: "SP2" } ]; console.log( list.sort(function(a, b) { if (a.id === "END3") { return 1; } return -1; }) ); 

Docs

Your sort comparison function is behaving inconsistently. The function is supposed to return < 0 , 0 , or > 0 , not just 1 or 0 . If it's not returning those values, you're giving sort the wrong information to work with, because you tell it any comparison in which a isn't the desired value is equal. It's not guaranteed that END3 will be passed as a at any point, so all comparisons will be "equal", so it's undefined what the result will be really. It's also possible that the inconsistency between SP1, END3 ("equal") and END3, SP1 ("greater") will affect the assumptions of the sorting algorithm.

 var list = [{id: "SP1"}, {id: "SP4"}, {id: "END3"}, {id: "SP2"}]; console.log(list.sort(function(a, b) { if (a.id === 'END3') { return 1; } else if (b.id === 'END3') { return -1; } else { return 0; } })); 

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