【问题标题】:How to swap array element from one position to another using lodash?如何使用 lodash 将数组元素从一个位置交换到另一个位置?
【发布时间】:2019-12-18 19:07:01
【问题描述】:

如何使用 lodash 库在 JavaScript 中将数组元素从一个位置交换到另一个位置? 像这样的:

_.swap(array, fromIndex, toIndex) //but this is not working

这是在线 lodash 测试仪的 link,我在其中测试了一些方法,但都没有成功

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 您希望数组项相互交换位置吗?就像您的示例中的 fromIndex 代替 toIndex 和 toIndex 代替 fromIndex 一样?
  • @StephenMIrving 是的!有什么方法可以让我使用 lodash 实现它?
  • 我在下面使用本机 JS 创建了一个您正在寻找的实现。出于某种原因,您是否需要在答案中使用 lodash 或者普通的老式香草 javascript 会这样做吗?

标签: javascript lodash


【解决方案1】:

如果您只想交换数组中两个元素的索引位置,您可以使用本机 JavaScript 快速实现。这是一个使用现代 ES6+ 语法的解决方案:

const swapArrayLocs = (arr, index1, index2) => {
  [arr[index1], arr[index2]] = [arr[index2], arr[index1]]
}

如果您从未见过像我上面使用过的解构赋值,您可以read about it here。当您需要交换两个变量(或在本例中为两个数组索引)的值时,对于此类问题,这是一种特别有用的技术。

以防万一您需要支持 Internet Explorer 等旧版浏览器,这里有一个 ES5 版本,它在语法上更加冗长:

var swapArrayLocs = function (arr, index1, index2) {
  var temp = arr[index1];

  arr[index1] = arr[index2];
  arr[index2] = temp;
}

您也可以在任一方法中使用function declaration(而不是上面的function expressions):

function swapArrayLocs(arr, index1, index2) {
  var temp = arr[index1];

  arr[index1] = arr[index2];
  arr[index2] = temp;
}

上述所有用于实现您正在寻找的功能的方法都将以相同的方式使用 - 就像任何其他函数调用一样。您将调用该函数,然后将您想要影响的数组以及您想要交换其值的两个数组索引传递给它。

const myArray = ["a", "b", "c", "d", "e", "f"];

swapArrayLocs(myArray, 0, 4);

// myArray is now: ["e", "b", "c", "d", "a", "f"]

这将操作数组,但我编写的函数不返回任何内容。如果你想改变它,你可以在最后添加一个 return 语句来传递 arr 或者可能包含两个被交换元素的数组......无论你需要什么来满足你的特定用例。

【讨论】:

  • 谢谢!这真的很有帮助。虽然我在寻找 lodash 但这回答了我的问题。
【解决方案2】:

方法一。

由于 Array.splice 在新数组中返回删除的值,所以你可以这样写:

const swapArrayLoc = (arr, from, to) => {
    arr.splice(from, 1, arr.splice(to, 1, arr[from])[0])
}

方法二。

使用临时变量。

const swapArrayLoc = (arr, from, to) => {
    let temp = arr[to];
    arr[to] = arr[from];
    arr[from] = temp;
}

注意:这些方法会改变原始数组,如果你不想改变它,复制到一个数组代替。

【讨论】:

    【解决方案3】:

    如果你想得到完整的数组结果...

    const swapElementPosition = (arr: any[], indexFrom: number, indexTo: number) => {
        const swappedIndices = [arr[indexFrom], arr[indexTo]] = [arr[indexTo], arr[indexFrom]]
        arr.forEach((aV, aVIndex) => {
            if (swappedIndices.indexOf(aV) === -1) {
                swappedIndices[aVIndex] = aV;
            }
        })
        return swappedIndices.filter((sI) => sI != null);
    }
    
    const a = new Date().toLocaleDateString().split('/').reverse();
    const b = [12, 13, 14, 15, 16];
    
    const aa = swapElementPosition(a, 2, 3);
    const bb = swapElementPosition(b, 3, 4);
    
    console.log(aa);
    console.log(bb)
    
    
    

    【讨论】:

      猜你喜欢
      • 2011-07-15
      • 2023-03-29
      • 2017-11-04
      • 2013-06-28
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 2023-01-05
      • 1970-01-01
      相关资源
      最近更新 更多