【问题标题】:How to move item from array after certain position and shift?如何在特定位置和移位后从数组中移动项目?
【发布时间】:2021-02-10 00:16:04
【问题描述】:

我需要管理一个带有依赖项的 todolist,它是一个包含对象的数组: 我需要带孩子并选择父母并重新订购物品。只有两个层次结构。

grandfather
 father
  child

例子:

data = [{id: 1, taskParentId: null}, {id:2, taskParentId: null}, {id:3, taskParentId: 1} {id:4, taskParentId: null}, {id:5, taskParentId: 2}, {id:6, taskParentId: 3}];

我需要这样的订单:

1-3--6
2-5
4

我正在尝试使用此功能订购

const swapArrayLocs = (arr, oldIndex, newIndex) => {
 if (newIndex >= arr.length) {
   let i = newIndex - arr.length + 1;
   while (i--) {
    arr.push(undefined);
   }
 }
 arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]);
 return arr;
};

我使用 taskParentId 获取元素的索引,并给出一个下一个 taskParent 的索引。

示例...索引为 6 的元素

swapArrayLocs(data, 6, parentIndex+1);

有时它可以工作,但有时顺序不受尊重...我可以使用一些顺序算法来解决它吗?

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    以下应该在两个索引之间执行干净的交换。预先设置好逻辑,并在每次要交换两个值时调用它。

    function swapArray(array, ind1, ind2) {
      let tempVal = array[ind1]
      array[ind1] = array[ind2]
      array[ind2] = tempVal
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-27
      • 1970-01-01
      • 2023-01-05
      • 1970-01-01
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多