Reputation: 13
I wanted to make a function that swaps 2 elements of an array in Javascript, so I created this piece of code:
let arrayOne = ["elementA","elementB","elementC","elementD","elementE","elementF","elementG","elementH","elementI"];
function swapThatFails(element1,element2) {
arrayOne[arrayOne.indexOf(element1)] = element2;
arrayOne[arrayOne.indexOf(element2)] = element1;
console.log("arrayOne = ",arrayOne);
}
swapThatFails ("elementA", "elementC");
However, it makes no change at all in the original array.
I managed to make it work by obtaining apart the indexes of the array I want to swap:
let arrayTwo = ["elementA","elementB","elementC","elementD","elementE","elementF","elementG","elementH","elementI"];
function swapThatWorks(element1,element2) {
let index1 = arrayTwo.indexOf(element1);
let index2 = arrayTwo.indexOf(element2);
arrayTwo[index1] = element2;
arrayTwo[index2] = element1;
console.log("arrayTwo = ",arrayTwo);
}
swapThatWorks ("elementA", "elementC");
To me, they both are the same apart from the fact that the second makes it in 2 steps so it looks easier to be understood.
Why the first one does not work but the second one does?
let arrayOne = ["elementA","elementB","elementC","elementD","elementE","elementF","elementG","elementH","elementI"];
let arrayTwo = ["elementA","elementB","elementC","elementD","elementE","elementF","elementG","elementH","elementI"];
function swapThatFails(element1,element2) {
arrayOne[arrayOne.indexOf(element1)] = element2;
arrayOne[arrayOne.indexOf(element2)] = element1;
console.log("arrayOne = ",arrayOne);
}
function swapThatWorks(element1,element2) {
let index1 = arrayTwo.indexOf(element1);
let index2 = arrayTwo.indexOf(element2);
arrayTwo[index1] = element2;
arrayTwo[index2] = element1;
console.log("arrayTwo = ",arrayTwo);
}
swapThatFails ("elementA", "elementC");
swapThatWorks ("elementA", "elementC");
Upvotes: 0
Views: 52
Reputation: 48230
Let's consider this
function swapThatFails(element1,element2) {
arrayOne[arrayOne.indexOf(element1)] = element2;
arrayOne[arrayOne.indexOf(element2)] = element1;
console.log("arrayOne = ",arrayOne);
}
Suppose the array is ['a','b']
and you call your flawed function with swapThatFails('a', 'b')
.
First you search for element1
and put element2
in there
arrayOne[arrayOne.indexOf(element1)] = element2;
Your array becomes ['b','b']
Then you search for element2
and put element1
there. But the array is already modified! The first occurence of element2
is not its original position but the new one, the one that has just been replaced in previous step.
Thus this
arrayOne[arrayOne.indexOf(element2)] = element1;
finds b
as the first element and replaces it with a
. And you get ['a','b']
. It's not what you expected!
If on the other hand you first search for elements, get correct indexes and then replace elements, it works as expected.
Upvotes: 2