如何使用lodash交换数组元素的位置?

17

如何使用lodash库在JavaScript中交换数组元素的位置? 类似这样:

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

这是在线 Lodash 测试器的链接,我在那里测试了一些方法,但没有一个起作用。

非常感谢您的任何帮助。谢谢!


你想让数组项彼此交换位置吗?就像你的例子中,fromIndex要取代toIndex的位置,而toIndex要取代fromIndex的位置? - Stephen M Irving
1
@StephenMIrving 是的!有没有办法可以使用Lodash来实现它? - Dungeon
1
我使用本地JS创建了您正在寻找的实现,如下所示。您是否因某种原因需要在回答中使用lodash,或者纯粹使用vanilla javascript也可以? - Stephen M Irving
3个回答

29

如果你只想要交换一个数组中两个元素的索引位置,你可以使用原生JavaScript很快地实现它。以下是使用现代ES6+语法的解决方案:

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

如果您从未见过像我上面使用的解构赋值,您可以在这里阅读有关它的信息。当您需要交换两个变量的值(或在这种情况下,两个数组索引)时,这是一种特别有用的技术。

如果您需要支持像Internet Explorer这样的旧浏览器,这里有一个ES5-版本,语法上略微冗长:

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

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

您还可以使用函数声明(而不是上面的函数表达式箭头函数),使用任一方法:

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"]

这将会操作数组,但是我所编写的函数并不返回任何东西。如果你希望改变这个情况,可以在末尾添加一个返回语句来返回 arr 或者可能包含两个被交换元素的数组...无论对于你的特定用例需要什么。


1
谢谢!那真的很有帮助。虽然我在寻找lodash,但这回答了我的问题。 - Dungeon
你有没有仔细阅读问题?问题中明确要求使用lodash。 - undefined

4

方法一:

由于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;
}

注意:这些方法将会改变原始数组,如果你不想改变它,可以使用复制到一个新数组的方式。

-1

如果你想要获取完整的数组结果...

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)



网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接