得到了一个似乎有效的解决方案:
var sortedCollection = [
{id: 3,x: 1,y: 1},
{id: 2,x: 1,y: 2},
{id: 1,x: 2,y: 1},
{id: 9,x: 2,y: 2},
{id: 5,x: 2,y: 3},
{id: 8,x: 2,y: 4},
{id: 7,x: 3,y: 1},
{id: 6,x: 3,y: 2},
{id: 4,x: 4,y: 1}
];
// example case
var movedItemIndex = 3 // change this value to which item you want to move
,movedItem = sortedCollection[movedItemIndex]
,movedItemId = movedItem.id
,referenceItemIndex = 6 // change this value to which item reference where you want to move your item
,referenceItem = sortedCollection[referenceItemIndex]
,referenceItemId = referenceItem.id
,relativePlacing = "above"; // second reference indicator one of (above, below, before, after)
sortedCollection = moveSortedCollectionItem( sortedCollection, movedItemIndex, referenceItem.x, referenceItem.y, relativePlacing );
sortedCollection = fixSortCollectionsNumericalXAndYSequence( sortedCollection, movedItemId, referenceItemId );
console.dir( sortedCollection );
function moveSortedCollectionItem( sortedCollection, itemIndex, refPosX, refPosY, relativePlace )
{
switch( true )
{
case( relativePlace == "above" || relativePlace == "before" ):
{
sortedCollection[itemIndex].x = refPosX
sortedCollection[itemIndex].y = refPosY
break;
}
case( relativePlace == "below" ):
{
sortedCollection[itemIndex].x = refPosX
sortedCollection[itemIndex].y = refPosY + 1
break;
}
case( relativePlace == "after" ):
{
sortedCollection[itemIndex].x = refPosX + 1
sortedCollection[itemIndex].y = refPosY
break;
}
}
return sortedCollection;
}
function fixSortCollectionsNumericalXAndYSequence( sortedCollection, movedItemId, referenceItemId )
{
// make sure we have the right sort order
sortedCollection.sort( sortByXAndY );
// return sortedCollection;
for( var i = 0, len = sortedCollection.length; i < len; i++ )
{
if( i == 0 && (sortedCollection[i].x != 1 || sortedCollection[i].y != 1) )
{
// first one must have x: 1 and y; 1 in order to make the whole thing work
sortedCollection[i].x = 1;
sortedCollection[i].y = 1;
}
else if( typeof sortedCollection[i-1] != 'undefined' /* has previous item */ )
{
sortedCollection[i] = _replaceXAndYFromItemWithPreviousItem( sortedCollection[i-1], sortedCollection[i] );
}
}
return sortedCollection;
}
function _replaceXAndYFromItemWithPreviousItem( previousItem, currentItem )
{
// case: previous item x and current item x are the same
if( currentItem.x == previousItem.x )
{
// set current item y = previous item y + 1
currentItem.y = previousItem.y + 1;
}
// case: current item x is not previous item x and not previous item x + 1
else if( currentItem.x != previousItem.x && currentItem.x != previousItem.x + 1 )
{
// set current item x = previous item x + 1; set current item y = 1
currentItem.x = previousItem.x + 1;
currentItem.y = 1;
}
return currentItem;
}
function sortByXAndY( model1, model2 )
{
var a = parseInt( model1.x )
,b = parseInt( model2.x )
if( a == b )
{
var c = parseInt( model1.y )
,d = parseInt( model2.y );
return c - d;
}
return a - b;
}
http://jsfiddle.net/69PXk/17/