Skip to content

Instantly share code, notes, and snippets.

@ajcrites
Forked from chris--young/gist:9630b7ac54e6e1adaa7f
Last active August 29, 2015 14:21
Show Gist options
  • Save ajcrites/874e1eeb2d4e45772a62 to your computer and use it in GitHub Desktop.
Save ajcrites/874e1eeb2d4e45772a62 to your computer and use it in GitHub Desktop.
var _ = require('lodash');
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;
// Move requested element
data.splice(move[key] - 1, 0, data.splice(_.findIndex(data, {id: move.id}), 1)[0]);
// Normalize order properties
data = data.map(function (elem, idx) {
elem[key] = idx + 1;
});
}
/**
* 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