通过计算属性值对Javascript对象进行排序

时间:2016-07-19 20:06:10

标签: javascript algorithm

我有项,位于(0,0)项目具有子项,其位置相对于存储。例如,children[2]的排名为(2,-8)

可以移动,当它移动时,它的净移动存储在movementdelta_xdelta_y中。在第一个示例中,父级向右移动:1,向上移动:0。我们可以说此项目正在向右移动。在第二个示例中,父级向右移动:1,向上移动:-2。我们可以说这个项目正在向下移动,因为它的右移小于它的移动。

我需要对children进行排序,以便在向右移动时, children 从右到左排序。下面我发布了两个场景及其预期输出。

Example image

var children = {
    2: {
        relative_position_x: 2,
        relative_position_y: -4
    }, // Positioned at (2, -4)
    4: {
        relative_position_x: 0,
        relative_position_y: -3
    }, // Positioned at (0, -3)
    1: {
        relative_position_x: 2,
        relative_position_y: 0
    } // Positioned at (2, 0)
}; // Relative to (0, 0)

var movement = {
    delta_x: 1,
    delta_y: 0
}; // Item is moving east (right)

// Another possible scenario, expecting output to be [2, 4, 1]
// var movement = {
//     delta_x: 1,
//     delta_y: -2
// }; // Item is moving south (forget about (east) delta_x because it's a smaller movement than delta_y)

console.log(sortedChildren); // expected [1, 2, 4] or [2, 1, 4] (from right-left)

1 个答案:

答案 0 :(得分:0)

这将支持所有内容,除非项目是对角线的(delta_x和delta_y具有相同的值),我仍然不确定如何对此实例进行排序。

var children = {
    2: {
        relative_position_x: 2,
        relative_position_y: -4
    }, // Positioned at (2, -4)
    4: {
        relative_position_x: 0,
        relative_position_y: -3
    }, // Positioned at (0, -3)
    1: {
        relative_position_x: 2,
        relative_position_y: 0
    } // Positioned at (2, 0)
}; // Relative to (0, 0)

var movement = {
    delta_x: 1,
    delta_y: 0
}; // Item is moving east (right)

var sortedChildren = [];

for (var childrenId in children) {
    if (Math.abs(movement.delta_x) == Math.abs(movement.delta_y)) {
        // diagonal
        console.log('Diagonal Movement: not supported');
    } else if (Math.abs(movement.delta_x) > Math.abs(movement.delta_y) && movement.delta_x > 0) {
        // right
        sortedChildren.push([children[childrenId], -children[childrenId].relative_position_x]);
    } else if (Math.abs(movement.delta_x) > Math.abs(movement.delta_y) && movement.delta_x < 0) {
        // left
        sortedChildren.push([children[childrenId], children[childrenId].relative_position_x]);
    } else if (Math.abs(movement.delta_x) < Math.abs(movement.delta_y) && movement.delta_y > 0) {
        // up
        sortedChildren.push([children[childrenId], -children[childrenId].relative_position_y]);
    } else if (Math.abs(movement.delta_x) < Math.abs(movement.delta_y) && movement.delta_y < 0) {
        // down
        sortedChildren.push([children[childrenId], children[childrenId].relative_position_y]);
    }
}

sortedChildren.sort(
    function(a, b) {
        return a[1] - b[1];
    }
);

console.log(sortedChildren);

Working JSFiddle