While attempting to reorganize an array of divs based on their positions relative to each other, I encountered a peculiar issue. After spending considerable time troubleshooting in CodePen, it became apparent that Chrome's sorting behavior gets erratic for arrays with ten or more elements.
var array = [0,1,2,3,4,5,6,7,8,9,10];
array.sort(function(a, b) {
return -1;
});
The output from Chrome was unexpected:
[0, 2, 3, 4, 1, 6, 7, 8, 9, 10, 5]
Further investigation revealed the underlying algorithm used by Chrome, which explains this anomaly. While familiar with using a-b
to sort, I needed a different approach due to the specific positioning criteria involved. The array consists of jQuery objects representing divs, and my goal is to arrange them visually based on vertical and horizontal proximity.
In response to initial attempts, I revised the comparison function to output either 1
, -1
, or 0
. Despite these adjustments, the results were not as intended.
Subsequently, a workaround was devised utilizing a forEach
loop to evaluate the items against each other and adjust the z-index
accordingly:
function setTileZIndex() {
var $tiles = $('.grid__item__wrap');
var coords = [];
$tiles.each(function(index) {
var topLeft = $(this).offset();
var obj = {
bottom: topLeft.top + $(this).height(),
left: topLeft.left,
top: topLeft.top,
right: topLeft.left + $(this).width(),
$this: $(this),
z: 9999
};
coords.push(obj);
});
coords.forEach(function(a) {
coords.forEach(function(b) {
if (a.bottom < b.top)
b.z += 4;
if (a.left > b.right)
b.z += 1;
})
});
coords.forEach(function(elt) {
elt.$this.css('z-index', elt.z);
});
}