Home > database >  How to change places in an Array?
How to change places in an Array?

Time:04-08

There's a list of 5 elements. Per default, the list (array) should show ["A", "B", "C", "D", "E"]. Every second the elements should rotate by one position:

List after 1 second: ["B", "C", "D", "E", "A"];

After 2 seconds: ["C", "D", "E", "A", "B"];

After 3 seconds: ["D", "E", "A", "B", "C"];

I'm learning and I need help. How would you solve this problem? This is my incorrect solution:

const testArray = ["A", "B", "C", "D", "E"];
    
    const swap = function(theArray, indexA, indexB) {
        let temp = theArray[indexA];
        theArray[indexA] = theArray[indexB];
        theArray[indexB] = temp;
    };
        
    swap(testArray, 0, 1);
    console.log(testArray);

CodePudding user response:

For no reason other than it's stupidly short.

let r = ['A','B','C','D','E'];
setInterval(_ => {r.push(r.shift());console.log(r)},1000)

CodePudding user response:

You can try array.shift method:

const arr = [1, 2, 3, 4, 5];

setInterval(() => {
  const firstElement = arr.shift();

  arr.push(firstElement);

  console.log(arr);
}, 1000);

CodePudding user response:

this is a shorter version of the swap

    const testArray = ["A", "B", "C", "D", "E"];
    
    const swap = function(theArray) {
        theArray.push(theArray.shift())
    };
        
    swap(testArray);
    console.log(testArray);

CodePudding user response:

You can shift the first element off the array, and then push it to the end of the array.

const arr = ['A', 'B', 'C', 'D', 'E'];

function swap(arr) {

  // Log the joined array
  console.log(arr.join(''));
  
  // `shift` the first element off the array
  // and `push` it back on
  arr.push(arr.shift());

  // Repeat by calling `swap` again after
  // one second, passing in the updated array
  setTimeout(swap, 1000, arr);

}

swap(arr);

Addition documentation

  • Related