简体   繁体   中英

Differences in JS Array.Sort IE 11 vs Chrome

I have a problem with a custom sort function I have written. In Chrome and Firefox the sort is firing properly and my records switch as needed. The issue arises when I run the code in IE 11. Here is my example https://jsfiddle.net/azb90cgv/8/

From what it looks like to me is that IE11 is switching the values entered into the sort function.

With dataset [A,B,C,D] Chrome and FF sort with by the combinations (A,B)(B,C)(C,D) for me IE 11 is comparing the items as (B,A)(C,B)(D,C)

This is an issue because my line return 1; isnt flipping my records IE11 is expecting a -1 value.

My goal: I want the data ordered by sequence, and when there is a duplicate switch the original order of the items. Am I overlooking something? Why is this running differently?

You need for a stable sort another property with the original order. This is used if two items have the same Sequence .

 var points = [{ id: 1, Sequence: 4 }, { id: 2, Sequence: 3 }, { id: 3, Sequence: 3 }, { id: 4, Sequence: 1 }] order = true; points.forEach(function (a, i) { a.order = i; }); document.getElementsByTagName('button')[0].onclick = function () { points.sort(function (a, b) { return a.Sequence - b.Sequence || (order ? a.order - b.order : b.order - a.order); }); order = !order; document.getElementById("out").innerHTML = JSON.stringify(points, 0, 4); } 
 <button>Swap</button> <pre id="out"></pre> 

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