我想上下移动数组项(按组)。这些项目按位置排序。
以下是当前数据:
| Index | Name | Pos | Group | Level
------------------------------------
| 0 | A | 11 | 1 | 1
| 1 | B | 12 | 1 | 1
| 2 | C | 21 | 3 | 2
| 3 | D | 22 | 3 | 2
| 4 | E | 23 | 3 | 2
| 5 | F | 31 | 2 | 2
| 6 | G | 32 | 2 | 2
我想将第2组中的每个项目都移到第3组以上。结果应:
| Index | Name | Pos | Group | Level
------------------------------------
| 0 | A | 11 | 1 | 1
| 1 | B | 12 | 1 | 1
| 2 | F | 21 | 2 | 2
| 3 | G | 22 | 2 | 2
| 4 | C | 31 | 3 | 2
| 5 | D | 32 | 3 | 2
| 6 | E | 33 | 3 | 2
我不知道如何以简单的方式做到这一点。我的尝试最终陷入混乱。的伪代码:
items = new Array(); // global array, filled with the data above
function move_up(group_id) {
// get group
var group = new Array();
for (var i = 0; i < items.length; i++) {
if (items.group_id == group_id)
group.push(items[i]);
}
// get parent group
var parent_group = new Array();
var parent_group_id = 0;
var level = group[0].level;
var get_next = false;
var x = 0;
for (var i = items.length-1; i >= 0; i--) {
if (items[i].group_id == group_id) {
get_next = true;
}
if (get_next == true &&
items[i].level == level &&
items[i].group_id != group_id) {
if (x == 0) {
parent_group_id = items[i].group_id;
}
if (items[i].group_id == parent_group_id) {
parent_group.push(items[i]);
}
x++;
}
}
parent_group.reverse();
// rebuild items array
var items_new = new Array();
var pos_1 = 1;
var pos_2 = 1;
for (var i = 0; i < items.length; i++) {
if (items[i].group_id == group_id) {
// do nothing
} else if (items[i].group_id == parent_group_id) {
// add group before parent group
for (var k = 0; k < group.length; k++) {
group[k].pos = pos_1 + pos_2;
items_new.push(group[k]);
}
// add parent group after group
for (var k = 0; k < parent_group.length; k++) {
parent_group[k].pos = pos_1 + pos_2;
items_new.push(parent_group[k]);
}
} else {
items[i].pos = pos_1 + pos_2;
items_new.push(items[i]);
}
}
return items_new;
}
第二次尝试:
function move_up(group_id, parent_group_id) {
items.sort(function(a, b) {
// what here? move group up, parent_group down. what, if the groups
// have not the same num of items?
// make sure, both items have the same level
if (a.level == b.level) {
// move group up
if (a.group_id == group_id) {
return -1;
}
// move parent group down
if (a.group_id == parent_group_id) {
return 1;
}
}
});
}
它不起作用,看起来很愚蠢。如果有人能给我一个思考冲动,我会很感激!
问题:
答案 0 :(得分:1)
结帐https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort 您需要定义使用Group Id的比较函数。