Function to queue walk in the Array, first turns the last in Javascript

Asked

Viewed 90 times

-1

need to do a function that in Array is registered:

Wesley
Welson
Gabriel

after being called, return:

Welson
Gabriel
Wesley

that in Javascript

  • 1

    This answers your question? How to access a circular array?

  • Definitely not, what I need is to return everything from the array, only changing the positions as shown in the question example, but maybe with this solution, I get there, creating subArrays within the array, then just change the position of the array

  • You want to rotate the array?

  • 1

    @Augustovasques, that, had not found the right word kkk, that’s right

2 answers

0

Based on the answers to the question "How to access a circular array?" we can reach a function that uses the function shift of array to always return a copy with the different orders:

const circular = (base) => {
  let arr = [...base];

  return () => {
    const primeiro = arr.shift();
    arr = [...arr, primeiro];
    return arr;
  }
};

const listar = circular(['Wesley', 'Welson', 'Gabriel']);

console.log(listar());
console.log(listar());

  • thank you very much, solved also, but I used the function of Augusto Vasques

0


Use the propagation syntax to make the left rotation of the array widgets.

let nomes = ["Wesley", "Welson", "Gabriel"]

let rotação = [...nomes.slice(1, nomes.length), nomes[0]]

console.log(rotação)

Only package as a function to fit the problem:

let nomes = ["Wesley", "Welson", "Gabriel"]

function rotacionarEsquesda(array) {
  return [...array.slice(1, array.length), array[0]]
}

console.log(rotacionarEsquesda(nomes))

  • It worked, I made it, thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.