Skip to content

Instantly share code, notes, and snippets.

@chris--young
Last active August 29, 2015 14:21
Show Gist options
  • Save chris--young/9630b7ac54e6e1adaa7f to your computer and use it in GitHub Desktop.
Save chris--young/9630b7ac54e6e1adaa7f to your computer and use it in GitHub Desktop.
reorders an array of objects based on a given key
var test_data = [
{ id: 'a', order_by: 1 },
{ id: 'b', order_by: 2 },
{ id: 'c', order_by: 3 },
{ id: 'd', order_by: 4 },
{ id: 'e', order_by: 5 },
{ id: 'f', order_by: 6 },
{ id: 'g', order_by: 7 },
{ id: 'h', order_by: 8 },
{ id: 'i', order_by: 9 }
];
/**
* reorders an array of objects
*
* @param: move {Object} - e.g. {id: 1, order_by: 4} to move 1 to place 4
* @param: data {Array} - array of objects to reorder
* @param: key {String} - key to order objects by
*/
function shift_order(move, data, key) {
if (move[key] > data.length || move[key] < 1)
return;
var shifted;
for (var index = 0; index < data.length; index++)
if (data[index].id === move.id) {
shifted = index;
break;
}
if (shifted !== 0 && !shifted)
return;
if (data[shifted][key] < move[key])
for (index = data[shifted][key]; index < move[key]; index++)
data[index][key]--;
else
for (index = move[key] - 1; index < data[shifted][key] - 1; index++)
data[index][key]++;
data[shifted][key] = move[key];
data.sort(function (a, b) {
if (a[key] < b[key])
return -1;
if (a[key] > b[key])
return 1;
return 0;
});
}
/**
* prints array of objects
*/
function print_data(data) {
for (var index = 0; index < data.length; index++)
console.log(data[index]);
}
console.log('pre-shift');
print_data(test_data);
shift_order({ id: 'a', order_by: 4 }, test_data, 'order_by');
console.log('post-shift 1');
print_data(test_data);
shift_order({ id: 'f', order_by: 2 }, test_data, 'order_by');
console.log('post-shift 2');
print_data(test_data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment