Skip to content
Advertisement

How to swap array element from one position to another using lodash?

How do I swap array element from one position to another in JavaScript using lodash library? Something like this:

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

This is the link for online lodash tester, where I tested some of the methods but none worked

Any help would be much appreciated. Thanks!

Advertisement

Answer

If what you want is just to to swap the index locations of two elements of an array, you can implement that yourself pretty quickly using native JavaScript. Here is a solution using modern ES6+ syntax:

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

If you’ve never seen a destructuring assignment like I used above, you can read about it here. It is an especially helpful technique with this kind of problem when you need to swap the value of two variables (or in this case, two array indices).

Just in case you need to support legacy browsers like Internet Explorer, here is an ES5- version that is a little more syntactically verbose:

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

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

You could also use a function declaration (rather than the function expressions above) with either method:

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

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

All of the above methods for implementing the functionality you’re looking for will be used in the same manner – just as with any other function call. You will call the function then pass it the array you want to affect, and the two array indices whose values you want to swap.

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

swapArrayLocs(myArray, 0, 4);

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

This will manipulate the array, but the functions I wrote do not return anything. If you wish to change that you could add a return statement to it at the end to pass arr back or possibly an array containing the two elements that were swapped… whatever you need for your particular use case.

Advertisement