Last active
November 2, 2021 16:01
-
-
Save eerohele/5195815 to your computer and use it in GitHub Desktop.
Swap two array elements (JavaScript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Swap the elements in an array at indexes x and y. | |
* | |
* @param (a) The array. | |
* @param (x) The index of the first element to swap. | |
* @param (y) The index of the second element to swap. | |
* @return {Array} The input array with the elements swapped. | |
*/ | |
var swapArrayElements = function (a, x, y) { | |
if (a.length === 1) return a; | |
a.splice(y, 1, a.splice(x, 1, a[y])[0]); | |
return a; | |
}; | |
swapArrayElements([1, 2, 3, 4, 5], 1, 3); //=> [ 1, 4, 3, 2, 5 ] |
@sillyslux: Thanks for the correction! I fixed the comment.
(On a side note, I really wish GitHub sent notifications when someone comments on your Gist.)
Another non-mutative ES6y version could be:
const swap = (arr, index1, index2) => arr.map((val, idx) => {
if (idx === index1) return arr[index2];
if (idx === index2) return arr[index1];
return val;
});
const foo = [1, 2, 3, 4, 5];
const swapped = swap(foo, 1, 3);
console.log(foo); //=> [1, 2, 3, 4, 5]
console.log(swapped); //=> [ 1, 4, 3, 2, 5 ]
Another non-mutative ES6y version could be:
const swap = (arr, index1, index2) => arr.map((val, idx) => { if (idx === index1) return arr[index2]; if (idx === index2) return arr[index1]; return val; }); const foo = [1, 2, 3, 4, 5]; const swapped = swap(foo, 1, 3); console.log(foo); //=> [1, 2, 3, 4, 5] console.log(swapped); //=> [ 1, 4, 3, 2, 5 ]
good way to change from O(1) to O(n)👍🏾
initial code seems more reasonable to me than this last one.
of course the code works but does it make sense to brute force the arr in order to swap two indexes?
what if list is large and you want to swap two indexes at the beginning and end of the list? seems a bit naive to me.
it's possible that i'm not seeing the wisdom in it so feel free to clarify if i'm wrong ;)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How could i switch the values of arrays so
arr
becomesarr = [5,6,7,8];
andarr2
becomesarr2 = [1,2,3,4];
?