skip to Main Content

I want to exchange the first value for the last, the second with the last but one and so on.

Like this:

Array = [0,1,2,3,4,5,6]

Array[0] –> Array[7] –> Array = [6,1,2,3,4,5,0]

I try to make this, but it didn’t work, it only makes the array blank:


var vetor = [],temp=0,b=vetor.length-1;

for (var i = 0;i<20;i++) {
    vetor[i] = Number(prompt("Digite um nĂºmero: " + i));
    temp = vetor[i];
    vetor[i] = vetor[b];
    b--;
    console.log(vetor[b]);
}
alert(vetor);

2

Answers


  1. The function works by creating a temp var to store the first element of the array – array[0]. Then it assigns the value of the last element to the first element and assigns the value of the temporary variable to the last element.

    function swap(array) {
      var temp = array[0];
      array[0] = array[array.length - 1];
      array[array.length - 1] = temp;
      return array;
    }
    
    const array = [0, 1, 2, 3, 4, 5, 6];
    console.log(swap(array));

    Reference:
    length

    Login or Signup to reply.
  2. I just created a function with paramateres(array and an iteration). For example if you want to change second and sixth element you must change iteration as 1.

    Example:

    Array is [0, 1, 2, 3, 4, 5, 6]
    changeArray(array, 0) will change 0 index and 6 index element.

    Array is [6, 1, 2, 3, 4, 5, 0]
    changeArray(array, 1) will change 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 iteration will be changed. If 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))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search