typescript 如何在更新位置时按位置插入和删除数组中的元素

mwkjh3gx  于 2023-04-13  发布在  TypeScript
关注(0)|答案(2)|浏览(314)

我有一个对象数组,它有一个position属性沿着其他属性,如下所示:

[{position: 1, ...otherProperties}, ...otherObjects]

在前端,对象按其位置显示和排序。
我正在寻找JavaScript函数来执行以下操作:
1.在指定的位置插入一个新对象(例如,在具有position的元素之前:1),并相应地更新其他元素的位置(例如,先前位置:1元素现在将是位置:2)。
1.从指定位置删除对象并相应地更新其余元素的位置。
我正在为这些功能的创建而挣扎

lymnna71

lymnna711#

您可以创建两个函数addElementremoveElement来添加或删除数组中的元素,同时确保位置正确排序。例如:

function addElement(arr, newPosition, newElement) {
  // Add a new element at the given position
  newElement.position = newPosition;
  arr.push(newElement);

  // Sort the array by position
  arr.sort((a, b) => a.position - b.position);

  // Update the position of elements
  arr.forEach((item, index) => {
    item.position = index + 1;
  });

  return arr;
}

function removeElement(arr, positionToRemove) {
  // Remove the element from the given position
  arr = arr.filter(item => item.position !== positionToRemove);

  // Update the remaining elements' positions
  arr.forEach((item, index) => {
    item.position = index + 1;
  });

  return arr;
}

使用方法:

let array = [
  { position: 1, prop: "a" },
  { position: 2, prop: "b" },
  { position: 3, prop: "c" },
];

let newArray = addElement(array, 1, { prop: "d" });
console.log(newArray);

newArray = removeElement(newArray, 3);
console.log(newArray);
zzlelutf

zzlelutf2#

您需要一个方法来解析数组的所有项并将新位置设置为所有项。

function fixPosition(arr) {
  arr.map((o, i) => o.pos = i+1)
  return arr
}

相关问题