I'm trying to write a script to change the order of an array of objects, ordered by an order property to let me move an element trough the array of objects I'm working on.
If I have:
[
{order: 0, name: 'a'},
{order: 1, name: 'b'},
{order: 2, name: 'c'}
]
And I want to give to b the order 0, the result of the function will be:
[
{order: 0, name: 'b'},
{order: 1, name: 'a'},,
{order: 2, name: 'c'}
]
Other examples:
// a to pos 2
input = [
{order: 0, name: 'a'},
{order: 1, name: 'b'},
{order: 2, name: 'c'}
]
output = [
{order: 2, name: 'a'},
{order: 0, name: 'b'},
{order: 1, name: 'c'}
]
// c to pos 1
input = [
{order: 0, name: 'a'},
{order: 1, name: 'b'},
{order: 2, name: 'c'}
]
output = [
{order: 0, name: 'a'},
{order: 1, name: 'c'},
{order: 2, name: 'b'}
]
This is my script so far:
var movedColumn = { order: 4, name: 'd' };
var newIndex = 1;
var oldIndex = movedColumn.order;
var columns = [ { order: 0, name: 'a' }, { order: 1, name: 'b' }, { order: 2, name: 'c' }, { order: 3, name: 'd' }, { order: 4, name: 'e' }, { order: 5, name: 'f' } ];
columns.sort(function asc(a, b) { return a.order - b.order; }).forEach(function(column) {
if (column.order >= newIndex && column.order < oldIndex) {
column.order += 1;
}
});
columns.find(function(column) {
return column.name === movedColumn.name;
}).order = newIndex;
http://codepen.io/FezVrasta/pen/XXgxWe?editors=001
It works well when I want to move b to order 0, but it doesn't work well if I want to move a to order 1.
I don't care about the order of the objects in the array, in my script I order them just to "pretty print" the result and for clarity.
What matters is the value of the order properties.
How can I fix it?
short version
I need to take an object and move it in the position defined by newIndex, shifting all the elements to prevent collisions (same order on two different objects)
bup without changing the order, and what's it supposed to be sorted by ?orderkey, this is why I don't care about the order of them in the array but I care only about whatordersays.spliceor do it manually with aforloop, and not use thesortmethod