Reputation: 1040
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!
Upvotes: 17
Views: 22252
Reputation: 1522
Lodash does not have a built-in function that swaps array elements at given indices. But if what you want to accomplish is just 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 swapArrayElements = (array, index1, index2) => {
// Checking parameters for errors
if (
index1 < 0 || index2 < 0 ||
index1 >= array.length || index2 >= array.length
) {
console.error('Invalid index passed to swapArrayElements()');
return array;
}
// Swapping elements and returning the mutated array
[array[index1], array[index2]] = [array[index2], array[index1]];
return array;
}
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).
There are also other ways you could handle the error checking in the function but using console.error() was the simplest and does not require you to use the function in a specific way, like wrapped in a try/catch block or returning a status object with the array and a potential error code. Whether you want to use one of these different ways to tackle the error handling, or if you want to return null
or undefined
instead of the original array in the event of an error, is up to you and your specific use case.
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 swapArrayElements = function (array, index1, index2) {
if (
index1 < 0 || index2 < 0 ||
index1 >= array.length || index2 >= array.length
) {
console.error('Invalid index passed to swapArrayElements()');
return array;
}
var temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
return array;
}
You could also use a function declaration (rather than the function expressions above) with either method:
function swapArrayElements(array, index1, index2) {
if (
index1 < 0 || index2 < 0 ||
index1 >= array.length || index2 >= array.length
) {
console.error('Invalid index passed to swapArrayElements()');
return array;
}
[array[index1], array[index2]] = [array[index2], array[index1]];
return array;
}
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"];
swapArrayElements(myArray, 0, 4);
// myArray is now: ["e", "b", "c", "d", "a", "f"]
These functions will manipulate the array it is given then return it. If you just want to mutate the array with the function and not return it, you can simply remove the return statements. If you want to preserve the original array by creating a duplicate and mutating and returning that, you just need to create a duplicate with the spread operator (or by using var newArray = array.slice()
if you need legacy support) before swapping the locations.
function swapArrayElements(array, index1, index2) {
if (
index1 < 0 || index2 < 0 ||
index1 >= array.length || index2 >= array.length
) {
console.error('Invalid index passed to swapArrayElements()');
return array;
}
const newArray = [...array]
[newArray[index1], newArray[index2]] = [newArray[index2], newArray[index1]];
return newArray;
}
Hope that this has been helpful!
Upvotes: 30
Reputation: 513
As Array.splice returns the removed value in a new array, so you can write it as this:
const swapArrayLoc = (arr, from, to) => {
arr.splice(from, 1, arr.splice(to, 1, arr[from])[0])
}
Use a temporary variable.
const swapArrayLoc = (arr, from, to) => {
let temp = arr[to];
arr[to] = arr[from];
arr[from] = temp;
}
Note: These ways will mutate the original array, if you don't want to mutate it, copy to an array instead.
Upvotes: 4