将数组元素从一个数组位置移动到另一个位置

新手上路,请多包涵

我很难弄清楚如何移动数组的元素。例如,给定以下内容:

var array = [ 'a', 'b', 'c', 'd', 'e'];

如何编写函数将元素 'd' 移动到 'b' 的左侧?

还是 'a' 'c'

移动元素后,应更新其余元素的索引。结果数组将是:

array = ['a', 'd', 'b', 'c', 'e']

这似乎应该很简单,但我无法理解它。

原文由 Mark Brown 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.9k
2 个回答

如果您想要 npm 上的版本, array-move 是最接近这个答案的,尽管它不是相同的实现。有关更多详细信息,请参阅其用法部分。可以在 npm 的 array.prototype.move 上找到此答案的先前版本(修改后的 Array.prototype.move)。


我在这个功能上取得了相当大的成功:

 function array_move(arr, old_index, new_index) {
 if (new_index >= arr.length) {
 var k = new_index - arr.length + 1;
 while (k--) {
 arr.push(undefined);
 }
 }
 arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
 return arr; // for testing
 };

 // returns [2, 1, 3]
 console.log(array_move([1, 2, 3], 0, 1));

请注意,最后一个 return 仅用于测试目的: splice 就地对数组执行操作,因此不需要返回。通过扩展,这一 move 是就地操作。如果您想避免这种情况并返回副本,请使用 slice

单步执行代码:

  1. 如果 new_index 大于数组的长度,我们希望(我假设)用新的 undefined 正确填充数组。这个小片段通过在数组上推送 undefined 来处理这个问题,直到我们有适当的长度。

  2. 然后,在 arr.splice(old_index, 1)[0] 中,我们拼接出旧元素。 splice 返回被拼接出来的元素,但它在一个数组中。在我们上面的例子中,这是 [1] 。因此,我们采用该数组的第一个索引来获取原始 1

  3. 然后我们使用 splice 将这个元素插入到 new_index 的位置。由于如果 new_index > arr.length 我们填充了上面的数组,它可能会出现在正确的位置,除非他们做了一些奇怪的事情,比如传入一个负数。

一个更好的版本来解释负指数:

 function array_move(arr, old_index, new_index) {
 while (old_index < 0) {
 old_index += arr.length;
 }
 while (new_index < 0) {
 new_index += arr.length;
 }
 if (new_index >= arr.length) {
 var k = new_index - arr.length + 1;
 while (k--) {
 arr.push(undefined);
 }
 }
 arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
 return arr; // for testing purposes
 };

 // returns [1, 3, 2]
 console.log(array_move([1, 2, 3], -1, -2));

这应该正确地考虑诸如 array_move([1, 2, 3], -1, -2) 之类的事情(将最后一个元素移动到倒数第二个位置)。结果应该是 [1, 3, 2]

无论哪种方式,在您最初的问题中,您都会在 c 之后为 a 执行 array_move(arr, 0, 2) 。对于 d 之前的 b ,您将执行 array_move(arr, 3, 1)

原文由 Reid 发布,翻译遵循 CC BY-SA 3.0 许可协议

我喜欢这样。它简洁而且有效。

 function arraymove(arr, fromIndex, toIndex) {
    var element = arr[fromIndex];
    arr.splice(fromIndex, 1);
    arr.splice(toIndex, 0, element);
}

注意:永远记得检查你的数组边界。

在 jsFiddle 中运行代码片段

原文由 SteakOverflow 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题