我很难弄清楚如何移动数组中的一个元素。例如,给定以下条件:

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

我怎么能写一个函数来移动元素'd'到'b'的左边?

还是c右边的a ?

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

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

这看起来应该很简单,但我无法理解它。


当前回答

一种方法是使用splice()从数组中删除项,然后再次使用splice()方法将删除的项插入到目标索引中。

Const array = ['a', 'b', 'c', 'd', 'e'] const newArray = moveItem(array, 3,1) //将元素从索引3移动到索引1 函数moveItem(arr, fromIndex, toIndex){ let itemRemoved = arr。splice(fromIndex, 1) //将删除的项赋值为数组 加勒比海盗。splice(toIndex, 0, itemRemoved[0]) //将itemRemoved插入目标索引 返回加勒比海盗 } console.log (newArray)

其他回答

找到并移动一个元素从第n个位置到第0个位置。

找到并移动“d”到第0个位置:

let arr = [ 'a', 'b', 'c', 'd', 'e'];
arr = [...arr.filter(item => item === 'd'), ...arr.filter(item => item !== 'd')];

这是一个非常简单的使用拼接的方法

Array.prototype.moveToStart = function(index) {
    this.splice(0, 0, this.splice(index, 1)[0]);
    return this;
  };

我们可以用多种方法将数组元素从一个位置移动到另一个位置。这里我用三种方法来解决这个问题。

使用拼接移动数组元素,其中时间复杂度为二次time - O(n^2)

function arrayMove(arr, oldIndex, newIndex) {
  const copiedArr = [...arr];
  const length = copiedArr.length;
  
  if (oldIndex !== newIndex && length > oldIndex && length > newIndex) {
    copiedArr.splice(newIndex, 0, copiedArr.splice(oldIndex, 1)[0]);
  }
  
  return copiedArr;
}

arrayMove([1,2,3,4], 0, 3) // [2,3,4,1]

使用flatMap移动数组元素,其中时间复杂度为线性时间- O(n)

function arrayMove(arr, oldIndex, newIndex) {
    const length = arr.length;
    const itemToMove = arr[oldIndex]

    if (oldIndex === newIndex || oldIndex > length || newIndex > length) {
        return arr;
    }

    return arr.flatMap((item, index) => {
        if (index === oldIndex) return [];
        if (index === newIndex) return oldIndex < newIndex ? [item, itemToMove] : [itemToMove, item];
        return item;
    })
}

arrayMove([1,2,3,4], 0, 3) // [2,3,4,1]

当时间复杂度为线性时间- O(n)时,使用reduce方法移动数组元素

function arrayMove(arr, oldIndex, newIndex) {
    const length = arr.length;
    const itemToMove = arr[oldIndex]

    if (oldIndex === newIndex || oldIndex > length || newIndex > length) {
        return arr;
    }

    return arr.reduce((acc, item, index) => {
        if (index === oldIndex) return acc;
        if (index === newIndex) return oldIndex < newIndex ? [...acc, item, itemToMove] : [...acc, itemToMove, item];
        return [...acc, item];
    }, [])
}

arrayMove([1,2,3,4], 0, 3) // [2,3,4,1]

您还可以检查以下要点:将数组元素从一个数组位置移动到另一个数组位置

一种方法是使用slice方法,按照您想要的顺序创建一个包含片段的新数组。

例子

var arr = [ 'a', 'b', 'c', 'd', 'e'];
var arr2 = arr.slice(0,1).concat( ['d'] ).concat( arr.slice(2,4) ).concat( arr.slice(4) );

Arr.slice(0,1)得到['a'] Arr.slice(2,4)给出['b', 'c'] Arr.slice(4)给出['e']

Const move = (from, to,…a) =>from === to ?A: (A .splice(to, 0,…Splice (from, 1)), a); Const moved = move(0, 2,…['a', 'b', 'c']); console.log(移动)