I just created a function with parameters (array and an iteration). For example, if you want to change the second and sixth element you must change the iteration as 1.
Example:
The array is [0, 1, 2, 3, 4, 5, 6]
changeArray(array, 0) will change the 0 index and 6 index element.
The array is [6, 1, 2, 3, 4, 5, 0]
changeArray(array, 1) will change the 1 index and 5 index element, so it will be like [6, 5, 2, 3, 4, 1, 0]
I added a constraint, because you can not divide forever. I calculated how many iterations will be changed. If the user adds any iteration which one is invalid, then it will return the array itself.
const changeArray = (array, iteration) => {
const length = array.length;
if(Math.floor(length / 2) < iteration) return array;
let values = {
first: {
index: iteration,
value: array[iteration]
},
last: {
index: length - iteration - 1,
value: array[length - iteration - 1]
}
}
array[values.last.index] = values.first.value;
array[values.first.index] = values.last.value;
return array;
};
const array = [6, 1, 2, 3, 4, 5, 0];
console.log(changeArray(array, 1))