Reputation: 115
I am having trouble with an excercise I have from school.
We have to swap two numbers in an array given two indexes. Here are the test cases.
Here is my code:
function swap(xs, i, j) {
var copyxs = xs.slice(0);
for (var a = 0; a < xs.length - 1; a++) {
if (xs.indexOf(copyxs[a]) == i) {
xs[a] = copyxs[j];
}
if (xs.indexOf(copyxs[a]) == j) {
xs[a] = copyxs[i];
}
}
return xs;
}
Upvotes: 1
Views: 104
Reputation: 4612
In case your teacher doesn't need you to modify input array you could do this with a map.
var input = [1,2,3,4,5,6];
var swap = (xs, i, j) => xs.map((x,index,arr) => {
if (index === i) return arr[j];
if (index === j) return arr[i];
return x;
});
console.log(swap(input, 2, 4));
var input = [1,2,3,4,5,6];
function swap(xs, i, j) {
return xs.map((x,index,arr) => {
if (index === i) return arr[j];
if (index === j) return arr[i];
return x;
});
}
console.log(swap(input, 2, 4));
Upvotes: 1
Reputation: 6706
No need to slice
array, you can just reassign the values at the given indices:
function swap(arr, i, j) {
var temp = arr[i]; //temporarily store original value at i position
arr[i] = arr[j]; //reassign value at i position to be value at j position
arr[j] = temp; //reassign value at j position to original value at i position
return arr;
}
Upvotes: 1
Reputation: 3266
As you have the indexes of the array that needs to be swapped, you don't have to slice and loop through the array elements to do that. Just keep one of the index values in a temp variable and re-assign the values as shown below :
function swap (xs, i, j){
var temp = xs[j];
xs[j] = xs[i];
xs[i] = temp;
return xs;
}
console.log(swap([1,2,3], 0, 1))
Upvotes: 1